A simple example of JavaScript parsing json formatted data
- 2020-03-30 04:32:47
- OfStack
The following string of json data is used to store the preloaded image path:
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 row through the name of json. Let's take a look at the code:
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;
}
The function returns the SRC of the row after execution.
var g = getData("p1");
console.log(g);
The result is: images/p1.jpg