Python JSON Basic Usage

Source: Internet
Author: User

JSON (JavaScript Object Notation) is a lightweight data interchange format that makes JSON an ideal data exchange language with a concise and clear hierarchy. Easy for people to read and write, but also easy to machine analysis and generation, and effectively improve the network transmission efficiency.

JSON functions

Use JSON functions to import the JSON library: import JSON.

json.dumps  将 Python 对象编码成 JSON 字符串json.loads  将已编码的 JSON 字符串解码为 Python 对象
Json.dumps

The json.dumps is used to encode a Python object into a JSON string.

Grammar
json.dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding="utf-8", default=None, sort_keys=False, **kw)
Instance

The following example encodes an array into JSON-formatted data:

#!/usr/bin/pythonimport jsondata = [ { 'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4, 'e' : 5 } ]json = json.dumps(data)print(json)

The result of the above code execution is:

[{"e": 5, "d": 4, "a": 1, "c": 3, "b": 2}]
Use parameters to format the output of JSON data:
import jsondata = [ { 'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4, 'e' : 5 } ]# 打开键值排序、缩进为 4、以',', ': '为分隔json = json.dumps(data, sort_keys=True, indent=4, separators=(',', ': '))print(json)

The result of the above code execution is:

[    {        "a": 1,        "b": 2,        "c": 3,        "d": 4,        "e": 5    }]
Json.loads

The json.loads is used to decode JSON data. The function returns the data type of the Python field.

Grammar
json.loads(s[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, **kw]]]]]]]])
Instance

The following example shows how Python decodes a JSON object:

#!/usr/bin/pythonimport jsonjsonData = '{"a":1,"b":2,"c":3,"d":4,"e":5}';text = json.loads(jsonData)print(text)

The result of the above code execution is:

{'a': 1, 'e': 5, 'd': 4, 'b': 2, 'c': 3}

Python JSON Basic Usage

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.