Home > Article > Web Front-end > Convert JS objects to JSON format data_json
Almost all current project data interactions use JQuery, so the processing flow is: front-end page data -> JS object -> jQuery submission -> python processing, and the other way is the other way around. Python certainly cannot directly process JS object data, so the JS object must be converted into a data format that python can handle (usually a dictionary). Similarly, when python fetches data and feeds it back to the front end, it must also convert the dictionary data into something that JS can handle. Object, this intermediate conversion data format is usually JSON.
1. Convert JS objects into JSON
Process: Read the front-end page data, assemble it into a JS object, and pass it to JSON through jQuery’s $.post() method python.
Processing: Reference a json2.js file and call the JSON.stringify() method. For example: var data = new Object(); var json_data = JSON.stringify(data);
Reading: python is very simple here, just use dict_data = json.loads(json_data)
2. Convert JSON to JS
Process: python assembles a dict data and converts it into JSON format and passes it to the front end, or the front end directly uses jQuery's $.getJSON() method Read the data in this JSON format
Processing: Use a jQuery method $.parseJSON() to convert the JSON format data into a JS object. For example: var json_data = $.getJSON(); var data = $.parseJSON(json_data);
Reading: There is no need to say more about the operation of JS objects
Here, python is required To convert the dictionary into JSON format data, just use the json.dumps() method
PS: The json2.js file can be downloaded by searching the Internet.