Home >Web Front-end >JS Tutorial >Example of fetching data from json using loop or if statement_javascript skills

Example of fetching data from json using loop or if statement_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:39:241377browse

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

{"head": [ 
{"text":"广州","id":"广州","pid":"广东省"}, 
{"text":"郑州","id":"郑州","pid":"河南省"}], 
}

As above, if you want to take out the id and pid data in sequence, you can only use a 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 + " "; //循环输出json数据 
head_pid += data.head[i].pid + " "; 
} 
$("#city").append("city:" + head_id); 
$("#city").append("province:" + head_pid);

In this way, the data in json will be output sequentially after data.

If you want to selectively 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 == "河南省") { //有选择的输出json数据 
head_pid += data.head[i].pid; 
} 
}

It should be noted that if there are multiple sets of data in the object, data.head.id is undefined because there is no indication of which set of data it is, such as data.head[0].id. If there is only one set of data in the object Group data can be output directly using data.head.id.

In addition, if the json data that is called is garbled in Chinese, on the one hand, check the jquery code called by json, on the other hand, it may be a problem with the file in which the json data is written.

The above is a little bit of learning from self-study json, record it.

(Note: When there is multiple data in the object, use it directly) (Note: When there is multiple data in the object, use it directly)

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn