6-2 how to read and write JSON data

Source: Internet
Author: User

By looking at Help (json.dump) and assist information (json.dumps), dump is converting the format to a file object, and dumps converts the format to a string.

First,Json.dumps ()

Json.dumps () Converts the Python object to JSON format.

1.Convert list toJSON format,
>>> L = [up,'abc', {'name':'Bob ' age': []]>>> json.dumps (l)'  [1, 2, "abc", {"Age": +, "name": "Bob"}]'
2. Convert Dictionary to JSON
>>> d = {'b': None,'a': 5,'c' :'abc'}>>> json.dumps (d)'{"A ": 5," C ":" abc "," B ": null}'

The conversion is basically the same as before the conversion, but the none of Python is converted to JSON null

Json.dumps () is converted to JSON after separating defaults think ', ' or ': ' (comma or colon spaces). You can specify the delimiter by separators, remove the space, the space as the display of some good-looking, do the transmission of more transmission.

>>> json.dumps (l,separators=[',',':']) ' ["abc", {"Age": +, "name": "Bob"}] '

sort the conversion results using the sort_keys parameter

>>> json.dumps (d,sort_keys=True)'{' A ': 5, ' B ': null, ' C ': ' abc '}' 
Twowill beJSON formatted data to Python object

Two functions for load () and loads ()

>>> D2 = json.loads ('{"A": 5, "C": "abc", "B": null}')>>> d2{ U 'a': 5, u'C': U'ABC' , u'b': None}
threeDump and load operations on files
>>> with open (R"C + + video \python Efficient Practice tips Note \6 data encoding and processing related topics \jsondemo.txt",' WB ' ) as F:    Json.dump (L, F)    Json.dump (d, F)

>>> with open (R"C + + video \python Efficient Practice tips Note \6 data encoding and processing related topics \jsondemo2.txt",'  w') as F:    Json.dump (L, F)    Json.dump (d, F)

6-2 how to read and write JSON data

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.