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