JSON module for Python

Source: Internet
Author: User
Tags string format

JSON (Java Script Object Notation): A lightweight data interaction format that is easier to read and write than XML, is easy to parse and generate, and JSON is a subset of JavaScript. The process of serializing and deserializing the JSON modules of Python is encoding and decoding, respectively.

    • Encoding: Converts a Python object encoding into a JSON string.
    • Decoding: Converts the JSON format string encoding into a Python object.

JSON provides four functions: Json.loads json.dumps json.load json.dump. Loads and dumps are used to handle strings, and load and dump are used to process the files.

    • Loads: Converting JSON to other formats, strings or file-related
    • Dumps: Convert other objects or formats to JSON format
    • Load: Converts the contents of a file into JSON data
    • Dump: Writing JSON data to a file

Program examples

  1. Convert dict format to JSON string format

Import= dict (name='huangdongju', age=25,message='something  ')print  (a) print = Json.dumps (a)  Print  (b)print (type (b))

Results:

2. Convert the JSON format to a dict

c = Json.loads (b)print ( type (c)) print ( c)print (c[' name '])

Results:

3. Write the JSON to the file

" " {"A": 1, "B": 2, "C": 3} " " With open ('a.txt','w') as F:    Json.dump ( JSONDATA,F)

Results:

4. Converting from a file to a JSON format

With open ('a.txt','r') as fr:    = json.load ( FR)    print  (    m)print (Type (m))

Results:

JSON module for Python

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.