Data preservation in reptiles----saving of json files

1. Introduction to json data

Purpose: Encodes a Python object into a JSON string, and decodes a JSON string into a Python object.

The json module provides APIs to convert in-memory Python objects into JSON sequences. JSON has the advantage of being implemented in many languages, especially JavaScript. It is widely used for communication between web servers and clients in REST APIs, and is also useful for inter-application communication needs.

1. JSON encoding and decoding

Python's default native types ( str , int , float , list , tuple , and dict ).


import json
data = {
    
    
	'name': 'ACME',
	'shares': 100,
	'price': 542.23
}
json_str = json.dumps(data)
print(json_str)
print(type(json_str))

# 保存
with open('data.json', mode='w', encoding='utf-8') as f:
	f.write(json_str)

From an unordered dictionary to an ordered string, this process is called serialization.

1. Problems with Chinese characters


import json
data = {
    
    
	'name': '张三',
	'shares': 100,
	'price': 542.23
}
# 将字典序列化为json
json_str = json.dumps(data)
# 写入 json 数据
with open('data.json', mode='w', encoding='utf-8') as f:
f.write(json_str)

这时的输出:
# filename:data.json
{
    
    "name": "\u9752\u706f", "shares": 100, "price": 542.23}

解决办法:
# ensure_ascii=False  不使用默认的unicode编码
 json_str = json.dumps(data, ensure_ascii=False)

2. Reading data


# 读取 json 数据
with open('data.json', 'r', encoding='utf-8') as f:
# 反序列化
	data = json.load(f)
# 打印数据
print(data)
print(data['name'])

3. Formatted output

The result in JSON is easier to read. The dumps() function accepts several parameters to output more readable results.


import json
data = {
    
    'a': 'A''b': (24)'c': 3.0}
print('DATA:'repr(data)) # DATA: {'a': 'A', 'b': (2, 4), 'c': 3.0}
unsorted = json.dumps(data)
print('JSON:', json.dumps(data)) # JSON: {"a": "A", "b": [2, 4], "c": 3.0}

explain:

Encoding and then re-decoding may not give exactly the same type of object.
In particular, tuples become lists. JSON is actually the same as a dictionary in Python. In fact, it is easy to find the corresponding relationship
between JSON data types and Python data types .

insert image description here

Guess you like

Origin blog.csdn.net/m0_74459049/article/details/130307215