[python] conversion between json and dictionary

JSON (JavaScript Object Notation) is a lightweight data interchange format.

The json module can be used in Python3 to encode and decode JSON data, which contains two functions:

json.dumps(): 对数据进行编码。将字典转成json
json.loads(): 对数据进行解码。将json转成字典

During the encoding and decoding process of json, Python's original type and json type will be converted to each other. The specific conversion comparison is as follows:

insert image description here

Reference Code

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("JSON 转换过来的字典:", data2)

It's all the same, the conversion is successful~

insert image description here

read json file

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

Guess you like

Origin blog.csdn.net/weixin_42468475/article/details/128947957