How to pass an array into laravel json? - json

Here my simple code..
$country=['Bangladesh','Pakistan'];
$capital=['Dhaka','Islamabad'];
return response()->json([
'country'=>$country,
'roll'=>$roll,
]);
If i run the above code ,the output will be like below..
{
"country": [
"Bangladesh",
"Pakistan"
],
"roll": [
'Dhaka',
'Islamabad'
]
}
But I want that my expected output will be like ..
EDIT: Following JSON is invalid (2 same key country)
{
{
"country":"Bangladesh",
"capital":"Dhaka"
},
{
"country":"Pakistan",
"capital":"Islamabad"
},
}

try this
$countries = ['India', 'Bangladesh', 'Pakistan'];
$capital = ['Delhi', 'Dhaka', 'Islamabad'];
$response = [];
foreach ($countries as $key => $country) {
$response[$key] = [
'country' => $country,
'capital' => $capital[$key],
];
}
return response()->json($response);
it will return
[{
"country": "India",
"capital": "Delhi"
},
{
"country": "Bangladesh",
"capital": "Dhaka"
},
{
"country": "Pakistan",
"capital": "Islamabad"
}
]

Your expected output is wrong. You simply cant have 2 same keys (country) in output json. You should have country and capital encapsulated in separate {}.

Related

How do i acess/map the name field of cities array inside the cities array in following json in dart/flutter

{
"cities": [
{
"cities": [
{
"name": "Adilabad",
},
{
"name": "Afjalpur",
},
]
},]
}
I am using Bloc pattern and trying to load the data in sugestions of SearchField.
I can access cities array like this -> state.cities.map((e) => e.city).toList();
but how can i access the name inside the array
You can do the following to get the city name.
Map map = {
"cities": [
{
"cities": [
{
"name": "Adilabad",
},
{
"name": "Afjalpur",
},
]
},
]
}; //´´
final cities = map['cities'][0]['cities'];
print(map['cities'][0]['cities']); // [{name: Adilabad}, {name: Afjalpur}]
print(cities[0]['name']); // Adilabad

ES6 filter an array of objects retrieving a field that is an empty array or does not contain certain value

I am trying to filter the following array
const matches = [
{
"match": "1",
"teams": [
[
{ "name": "david"},
{ "name": "tom"}
],
[
{ "name": "liam"},
{ "name": "noah"}
]
]
},
{
"match": "2",
"teams": [
[
{ "name": "david"},
{ "name": "tom"}
],
[
{ "name": "oliver"},
{ "name": "elijah"}
]
]
},
{
"match": "3",
"teams": []
}
]
I want to retrieve the objects where the teams array is empty, or "oliver" does not belong to the teams. It should retrieve match "1" and "3"
I tried the following
matches.filter(match => match.teams.length === 0 || !match.teams.includes({ name: "oliver" })
matches.filter(match => match.teams.length === 0 || !match.teams.some(team => team.name === "oliver" })
but I am getting the 3 objects
match.teams is an array of arrays of players
try this
matches.filter(match =>
match.teams.length === 0 ||
match.teams.every(team =>
team.every(player => player.name !== "oliver" )
)
)
// use array.flat method. teams is arrays of arrays
const result=matches.filter(match=>{
if(!match.teams.length){
return true;
}
const teamArray=match.teams.flat(1);
console.log(teamArray);
const search=teamArray.find(player=>player.name!=="oliver");
if(search){
return true;
}
return false;
});

React : filter json object with array of multiple possible values

I have a json object
I imported it in the react component like this
import data from "../data/data.json";
This is my json object
{
"Cocktail": [
{
"id": 1,
"name": "PL",
"illustration": "img1",
"ingredient": [{"percent": "1/10","ingredientname": "br"},
{"percent": "4/10","ingredientname": "or"},
{"percent": "5/10","ingredientname": "vo"}]
},
...
{
"id": 3,
"name": "AN",
"illustration": "img3",
"ingredient": [{"percent": "2/10","ingredientname": "br"},
{"percent": "2/10","ingredientname": "li"},
{"percent": "6/10","ingredientname": "ri"}
]
}
]
}
I have this array
ingred = ["br", "or"]
I want to filter the json object file :
ingredientsname which have one of the corresponding value of ingred array and return the name of each element associated
I tried this
return (
<>
{
data.Cocktail
.map((cocktail) => {
return (
<>
{
cocktail.ingredient.filter(ingredientcocktail => ingredientcocktail.ingredientname === ingred).map((ingredientcocktail) => {
return (
<span key={cocktail.name}>
</span>
);
})
}
</>
);
})
}
</>
);
But it doesn't work : I don't know how to pass through items of the second array for the filtering.
Can someone could help me ?
I think I found a solution :
data.Cocktails
.map((cocktail) => {
return (
<>
{
cocktail.ingredient
.filter(ingredientcocktail => ingred .includes(ingredientcocktail.ingredientname))
.map((ingredientcocktail) => {
return (
<div key={ingredientcocktail.ingredientname}>
{cocktail.name}
</div>
);
})
}
</>
);
})
}
Thank you for your answers.
Sorry, can't help you with ReactJs, but this should work in "plain" JS:
let obj = {
"Cocktail": [
{
"id": 1,
"name": "PL",
"illustration": "img1",
"ingredient": [{"percent": "1/10","ingredientname": "br"},
{"percent": "4/10","ingredientname": "or"},
{"percent": "5/10","ingredientname": "vo"}]
},
{
"id": 3,
"name": "AN",
"illustration": "img3",
"ingredient": [{"percent": "2/10","ingredientname": "br"},
{"percent": "2/10","ingredientname": "li"},
{"percent": "6/10","ingredientname": "ri"}
]
},
{
"id": 4,
"name": "asdasd",
"illustration": "asdasd",
"ingredient": [{"percent": "2/10","ingredientname": "asdasd"},
{"percent": "2/10","ingredientname": "asdasd"},
{"percent": "6/10","ingredientname": "asdasd"}
]
}
]
};
let wanted = ["br", "or"]
let res = obj.Cocktail.filter(
el => el.ingredient.some(
i => wanted.some(w => w == i.ingredientname)
)
).map(cocktail => cocktail.name);
console.log(res)
(This is not meant to be "the most efficient way", so please, if you have more efficient way to do it, feel free to make an answer, and not complain about it on the comments)

How to store and retrieve nested JSON array in laravel 6

I am trying to retrieve the data saved as json in mysql. My migration looks like below:
Schema::create('items', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name')->nullable();
$table->json('add_ons')->nullable();
$table->timestamps();
});
I have tried saving the below JSON from postman and it saved perfectly.
{
"itemName": "chicken",
"addons": {
"required": false,
"min": 2,
"max": 3,
"data": [
{
"name": "sauces",
"type": [
{
"name": "white sauce",
"type": [
{
"name": "whiteOne",
"price": 10
},
{
"name": "whiteTwo",
"price": 20
}
]
},
{
"name": "red sauce",
"price": 10
}
]
}
]
}
}
Now, I trying to retrieve the price of 'whiteOne' under 'white sauce' and getting nothing other than null or laravel error response.
I have tried
Item::whereJsonContains('add_ons->data->name','sauces')->get()
Item::whereJsonContains('add_ons->data->name','sauces')->find(16)
After saving the 'add_ons' column has below data:
{
"required": false,
"min": 2,
"max": 3,
"data": [
{
"name": "sauces",
"type": [
{
"name": "white sauce",
"type": [
{
"name": "whiteOne",
"price": 10
},
{
"name": "whiteTwo",
"price": 20
}
]
},
{
"name": "red sauce",
"price": 10
}
]
}
]
}
Can anyone help me ?
I used this function to get the value of the index.
public function search($array, $key, $value) {
// RecursiveArrayIterator to traverse an
// unknown amount of sub arrays within
// the outer array.
$arrIt = new \RecursiveArrayIterator($array);
// RecursiveIteratorIterator used to iterate
// through recursive iterators
$it = new \RecursiveIteratorIterator($arrIt);
foreach ($it as $sub) {
// Current active sub iterator
$subArray = $it->getSubIterator();
if ($subArray[$key] === $value) {
//$result[] = iterator_to_array($subArray);
$result = iterator_to_array($subArray);
}
}
return $result;
}
Now when I pass the values in the function I get the appropriate values.
$item = Item::where('id','=',16)->first();
$res = $this->search($item->add_ons['data'], 'name', 'whiteTwo');
echo $res["name"]." - ".$res['price'] ."<br>";

react native json image

I want to print out JSON images as a variable.
This is my local JSON file (JsonData.json):
{
"appetizer": [
{
"num": "appetizer1",
"name": "salad",
"condition": [ "1", "2" ],
"image": "./appetizer/salad.png"
},
{
"num": "appetizer2",
"name": "soup",
"condition": [ "2", "3" ],
"image": "./appetizer/soup.png"
},
…
],
"main": [
{
"num": "main1",
"name": "beef",
"condition": [ "1" ],
"image": "./main/beef.png"
},
{
"num": "main2",
"name": "fish",
"condition": [ "2", "3" ],
"image": "./main/fish.png"
},
…
]
}
I filtered the name when condition="2". (salad,soup,fish)
This is the code for filtering name:
const newArray1 = [...JsonData["apptizer"], ...JsonData["main"]];
const JsonResult = newArray1.filter(item => {
if(item.condition.indexOf("2") !== -1) return item.name;
});
AND I want to get the image when condition="2".
How can I get them? And How can I print out them?
Do I have to use base64? If so, Can you tell me how to use it?
I saw the explanation, but I can't understand it.
And I imported JSON file this way (I've been correctly using it):
var JsonData = require('./JsonData.json');
You can use below code:
let mainObject = JSON.parse(JSON.stringify(data))
let allKeys = Object.keys(mainObject)
let finalObject = []
allKeys.map((value, index) => {
let array = mainObject[value]
array.map((aryObject, aryIndex) => {
let condition = aryObject['condition']
if (condition.includes('2')) {
finalObject.push(aryObject)
}
})
})
alert(JSON.stringify(finalObject))
You can import data in top of screen:
import { data } from './data';
You can add below text in data.js:
export const data = {
"appetizer": [
{
"num": "appetizer1",
"name": "salad",
"condition": ["1"],
"image": "./appetizer/salad.png"
},
{
"num": "appetizer2222",
"name": "soup",
"condition": ["2", "3"],
"image": "./appetizer/soup.png"
},
],
"main": [
{
"num": "main1",
"name": "beef",
"condition": ["1"],
"image": "./main/beef.png"
},
{
"num": "main2",
"name": "fish",
"condition": ["21", "3"],
"image": "./main/fish.png"
},
]
}
You can use Object#values to get the arrays corresponding to appetizer and main and then Array#flat to extract the nested objects into a transformed array. Then use the Array#filter (which you are already using) to filter out only the required objects based on your condition and then Array#map to get the name and image values out of every filtered object into an array of objects.
Please consider following snippts
const jsonData = {"appetizer":[{"num":"appetizer1","name":"salad","condition":["1","2"],"image":"./appetizer/salad.png"},{"num":"appetizer2","name":"soup","condition":["2","3"],"image":"./appetizer/soup.png"}],"main":[{"num":"main1","name":"beef","condition":["1"],"image":"./main/beef.png"},{"num":"main2","name":"fish","condition":["2","3"],"image":"./main/fish.png"}]};
const filteredValues = Object.values(jsonData)
.flat()
.filter(o => o.condition.includes('2'))
.map(({name, image}) => ({ name, image }));
console.log(filteredValues);
The output of the above code will be an array of objects having the following structure
[{
"name": SOME_NAME,
"image": SOME_PATH
},
{
"name": SOME_NAME,
"image": SOME_PATH
},
...
]
You can use the above array to retrieve your image path and display it accordingly.
I think you shouldn't be worried about base64 as images are stored locally and path will be sufficient to display the image.
Hope this will help!!!
Side Note: You can avoid the Array#flat part as you are already doing it manually [...JsonData["apptizer"], ...JsonData["main"]] but flat will be handy in case there are more keys in jsonData that need to be considered.