Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

A simple example of JavaScript parsing json format data


May 08, 2021 JSON


Table of contents


This article obtains jason node data through the for loop, and the required friends can refer to the following string of jason data to store preloaded picture paths:


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"
    }
]

Here's a function that gets the path src for each line of jason, so let's look at the 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;
}

The src of the row is returned after the function is executed.


The code is as follows:
var g = getData("p1");
console.log(g);

Once output, you can see that the result is: images/p1 .jpg

JS objects and JSON format data are converted to each other

The mutual conversion of JS object and JSON format data is actually two problems: JS object is converted to JSON format data, JSON format data is converted to JS object. /b20> The current project data interactions are almost always with JQuery, so the process is: front-end page data -JS object-jQuery commit-python processing, the other is upside down. P ython certainly can't process JS object data directly, so convert JS objects into a data format that python can handle (usually dictionary diction), just as python takes data back to the front end and converts dictionary data into objects that JS can process, which is usually JSON.

First, the JS object is converted to JSON

Process: Read the front-end page data, assemble it into a JS object, and pass it to python via jQuery's $.post() method.

Processing: Refers to a json2 .js file and calls the JSON.stringify() method. F or example: var data s new Object (); v ar json_data = JSON.stringify(data);

Read: python here is very simple, dict_data with the message s . . . json.loads (json_data) OK

Second, JSON converts to JS

Process: python assembles a dikt data and transfers it to the front end in JSON format, or reads the JSON format data directly through jQuery's $.getJSON() method

Processing: Transfer JSON-formatted data to a JS object using one of jQuery's methods,$.parseJSON(). F or example: var json_data .getJSON(); v ar data = $.parseJSON(json_data);

Read: JS doesn't have to say much about the operation of the image

Here, python will convert the dictionary into JSON format data, using the json.dumps() method