Conversion between JS objects and JSON format data _ json

Source: Internet
Author: User
This problem occurs recently. JS objects and JSON format data are converted to each other. In fact, there are two problems: Converting JavaScript objects into JSON-format data, and converting JSON-format data into JS objects. Currently, almost JQuery is used for project data interaction, so the processing process is as follows: front-end page data-JS object-jQuery submit-python processing, another is to reverse. Python certainly cannot directly process JS object data, so it is necessary to convert JS objects into a data format (usually dictionary dict) that python can process. Similarly, when python obtains data feedback to the front-end, it also needs to convert Dictionary data into objects that can be processed by JS. The intermediate conversion data format is usually JSON.

1. Convert JS objects to JSON

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

Processing: reference A json2.js file and call the JSON. stringify () method. For example: var data = new Object (); var json_data = JSON. stringify (data );

Read: python is easy here. It's okay to use dict_data = json. loads (json_data ).

Ii. Convert JSON into JS

Process: python assembles a dict data and transfers it to the front end in JSON format, or the front end directly reads the data in JSON format using the $. getJSON () method of jQuery.

Processing: Use jQuery's method $. parseJSON () to convert JSON-format data into JS objects. For example: var json_data = $. getJSON (); var data = $. parseJSON (json_data );

Reading: javascript image operations are unnecessary.

Here, python needs to convert the dictionary into JSON format data, just use the json. dumps () method.

PS: The json2.js file can be downloaded after being searched online.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.