Reputation: 488
I have a json that looks like this.
How can I retrieve the information inside the group "demo", without looking into the array like: json['data'][0]
I wanted to retrieve the info reading the first value.. "group" and if it matches demo, get all that group info.
{
"filter": "*",
"data": [
{
"group": "asdasd",
"enable": 1,
"timeout": 7,
"otpMode": 0,
"company": "cool",
"signature": "ou yeah",
"supportPage": "",
"newsLanguages": [
0,
0,
0,
0,
0,
0,
0,
0
],
"newsLanguagesTotal": 0
},
{
"group": "demo",
"enable": 1,
"timeout": 7,
"otpMode": 0,
"company": "pppppooo",
"signature": "TTCM",
"supportPage": "http://www.trz<xa",
"newsLanguages": [
0,
0
],
"newsLanguagesTotal": 0
}
]
}
So long I have:
let json = JSON.parse(body);
//console.log(json);
console.log(json['data'][1]);
Which access to "demo"
Upvotes: 0
Views: 47
Reputation: 560
If the key "group" is missing for any of the records, a simple check (similar to the code provided by @MarkSkayff) will give an error. To fix this, check to see if json["data"][i] exists and check if json["data"[i]["group"] also exists
function json_data(){
var res=[]
for (var i in json["data"]){
if(json["data"][i] && json["data"][i]["group"] === "demo"){ //strict comparison and boolean shortcircuiting
res.push(json["data"][i])
}
}
console.log(res)
}
The result is stored in res
Not enough space here but for more on boolean short circuiting read this explanation of dealing with irregular JSON data
Upvotes: 0
Reputation: 2691
I suggest you use the filter()
json.data.filter(function(item){
return item.group === "demo";
});
this will return the objects that have "demo" in the group property
Or if you want to get fancy es6 with it
json.data.filter(item => item.group === "demo");
Upvotes: 1
Reputation: 1384
Process each "data item" and check for the group value. If it matches, then do something.
var json = JSON.parse(jsonStr);
for(var i=0;i<json.data.length;i++){
if(json.data[i].group == "demo"){
var group = json.data[i];
// Process the group info
}
}
Upvotes: 1