Sample data from json with a loop or if statement

  • 2020-03-30 03:45:27
  • OfStack

First, for example, json data is written as follows:


{"head": [ 
{"text":" Guangzhou ","id":" Guangzhou ","pid":" Guangdong province, "}, 
{"text":" zhengzhou ","id":" zhengzhou ","pid":" Henan province "}], 
}

As above, if you want to take out the id and pid data in turn, you can only use the loop, the code is as follows:


var head_id = ""; 
var head_pid = ""; 
for (var i = 0; i < data.head.length; i++) { 
head_id += data.head[i].id + " "; //Loop out the json data
head_pid += data.head[i].pid + " "; 
} 
$("#city").append("city:" + head_id); 
$("#city").append("province:" + head_pid);

This will output the data in json in turn after the data.

If you want to have selective output, you need to add an if condition. The code is as follows:


for (var i = 0; i < data.head.length; i++) { 
if (data.head[i].pid == " Henan province ") { //Selected output json data
head_pid += data.head[i].pid; 
} 
}

Note that if there are more than one set of data in the object, the data.head.id is undefined, because it is not indicated which set of data, such as data.head[0].

In addition, if the json data called out, Chinese garbled code, on the one hand to see the jquery code json calls, on the other hand, may be the problem of writing json data files.

So that's a little bit of what I learned from json on my own.

(note: when there are multiple data in the object, use directly)


Related articles: