We often encounter the problem of switching D between JS objects and JSON data in the development of the system, especially when using AJAX technology. In fact, that is two problems: JS object conversion into JSON format data, JSON format data conversion into JS objects
The current project data interaction is almost all in jquery, so the process is: front-end page data-"JS Object-" jquery Commit-"python processing, the other is the reverse." Python must not directly deal with JS object data, so to convert the JS object into a python can handle a data format (usually the dictionary dict), the same, Python data feed back to the front-end also to the dictionary data into JS can handle the object, This intermediate conversion data format is usually JSON.
One, JS object conversion into JSON
Process: Reads the front-end page data, assembles it into a JS object, and passes it to Python via the $.post () method of jquery.
Processing: Refers to a json2.js file and calls the Json.stringify () method.
For example:
var data = new OB ject ();
var json_data = json.stringify (data);
READ: Python here is very simple, with dict_data = Json.loads (json_data) on the OK
Two, JSON conversion into JS
Process: Python assembles a dict data and passes it to the front end in JSON format, or the front end reads this JSON-formatted data directly through the $.getjson () method of jquery
Processing: Using a method of jquery $.parsejson () converts JSON-formatted data into a JS object.
For example:
var json_data = $.getjson ();
var data = $.parsejson (Json_data);
READ: JS to the image of the operation will not have to say more
Here, Python converts the dictionary into JSON-formatted data, using the Json.dumps () method.
PS:json2.js This file can be downloaded by searching the Internet.