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"
-
1Are you asking how you would find all the objects in the data array where the 'group' property is "demo"?Ju66ernaut– Ju66ernaut2017年01月31日 22:44:02 +00:00Commented Jan 31, 2017 at 22:44
-
yes, but looking for that value in a loop ... not directly like json['data'][1]arnoldssss– arnoldssss2017年01月31日 22:45:02 +00:00Commented Jan 31, 2017 at 22:45
3 Answers 3
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
}
}
Comments
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");
Comments
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