Python3 JSON data analysis

JavaScript Object Notation is a lightweight data exchange format. It is based on a subset of ECMAScript.

The Json module can be used to code JSON data in Python3, which contains two functions:

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

During jason's codec process, Python's original and json types are converted to each other, as follows:

Python encodes the corresponding table for JSON type conversion:

Python Json
dict object
list, tuple array
Str string
int, float, int- & float-derived Enums number
True true
False false
None Null

JSON decodes the corresponding table for Python type conversion:

Json Python
object dict
array list
string Str
number (int) Int
number (real) float
true True
false False
Null None

json.dumps and json.loads instances

The following example demonstrates the conversion of the Python data structure to JSON:

#!/usr/bin/python3

import json

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

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

The above code output results in:

Python 原始数据: {'url': 'http://www.w3cschool.cn', 'no': 1, 'name': 'W3CSchool'}
JSON 对象: {"url": "http://www.w3cschool.cn", "no": 1, "name": "W3CSchool"}

As can be seen from the results of the output, the simple type is encoded to be very similar to its original repr() output.

Then, in the above example, we can convert a JSON-encoded string back to a Python data structure:

#!/usr/bin/python3

import json

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

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'])

The above code output results in:

ython 原始数据: {'name': 'W3CSchool', 'no': 1, 'url': 'http://www.w3cschool.cn'}
JSON 对象: {"name": "W3CSchool", "no": 1, "url": "http://www.w3cschool.cn"}
data2['name']:  W3CSchool
data2['url']:  http://www.w3cschool.cn

If you are working with a file instead of a string, you can use json.dump() and json.load() to encode and decode JSON data. For example:

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

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

For more information, please refer to: https://docs.python.org/3/library/json.html