Home  >  Article  >  Web Front-end  >  Simple example of JavaScript parsing json format data_javascript skills

Simple example of JavaScript parsing json format data_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:28:051243browse

The following string of json data is used to store the preloaded image path:

Copy code The code is as follows:

var imgData = [
{ name: "p1", src: "images/p1.jpg" },
{ name: "p2", src: "images/p2.jpg" },
{ name: "p3", src: "images/p3.jpg" },
{ name: "p4", src: "images/p4.jpg" },
{ name: "p5", src: "images/p5.jpg" }
]

The following function can get the path src of each line of json through the name of the line. Let us take a look at the code:

Copy code The code is as follows:

function getData(name) {
var picArr = imgData;
var picSrc;
for (var i = 0; i < picArr.length; i ) {
var cur_person = picArr[i];
if (cur_person.name == name) {
picSrc = cur_person.src;
}
}
return picSrc;
}

After the function is executed, the src of the line will be returned.

Copy code The code is as follows:

var g = getData("p1");
console.log(g);

After output, you can see the result: images/p1.jpg

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