Strange corner of python3 (9): JSON data parsing

JSON (JavaScript Object Notation) is a lightweight data interchange format. It is based on a subset of ECMAScript.
In Python3, you can use the json module to encode and decode JSON data. It contains two functions:

  • json.dumps(): Encode the data.
  • json.loads(): Decode the data.

In the process of json encoding and decoding, the original type of python and the json type will be converted to each other. The specific conversion comparison is as follows:
Python encoding to JSON type conversion correspondence table:
write picture description here
JSON decoding to Python type conversion correspondence table:
write picture description here
json.dumps and json.loads Example
The following example demonstrates the conversion of a Python data structure to JSON:
The repr() function converts an object into a form that can be read by the interpreter. Returns an object in string format.

#!/usr/bin/python3

import json

# Python 字典类型转换为 JSON 对象
data = {
    'no' : 1,
    'name' : 'Runoob',
    'url' : 'http://www.runoob.com'
}

json_str = json.dumps(data)
print ("Python 原始数据:", repr(data))
print(type(repr(data)))
print("JSON 对象:", json_str)
print(type(json_str))

The output of executing the above code is:

Python 原始数据: {'name': 'Runoob', 'no': 1, 'url': 'http://www.runoob.com'}
<class 'str'>
JSON 对象: {"name": "Runoob", "no": 1, "url": "http://www.runoob.com"}
<class 'str'>

As can be seen from the output, the simple type is very similar to the output of its original repr() after encoding.
Following the above example, we can convert a JSON-encoded string back into a Python data structure:

#!/usr/bin/python3

import json

# Python 字典类型转换为 JSON 对象
data1 = {
    'no' : 1,
    'name' : 'Runoob',
    'url' : 'http://www.runoob.com'
}

json_str = json.dumps(data1)
print ("Python 原始数据:", repr(data1))
print ("JSON 对象:", json_str)

# 将 JSON 对象转换为 Python 字典
data2 = json.loads(json_str)
print ("data2['name']: ", data2['name'])
print ("data2['url']: ", data2['url'])
## 执行以上代码输出结果为:
Python 原始数据: {'name': 'Runoob', 'no': 1, 'url': 'http://www.runoob.com'}
JSON 对象: {"name": "Runoob", "no": 1, "url": "http://www.runoob.com"}
data2['name']:  Runoob
data2['url']:  http://www.runoob.com

If you're dealing with files rather than strings, you can use json.dump() and json.load() to encode and decode JSON data. E.g:

# 写入 JSON 数据
with open('data.json', 'w') as f:
    json.dump(data, f)

# 读取数据
with open('data.json', 'r') as f:
    data = json.load(f)

More references:
https://docs.python.org/3/library/json.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324889060&siteId=291194637