json 模块提供了一种很简单的方式来编码和解码JSON数据。 其中两个主要的函数是 json.dumps() 和 json.loads()。
1.json.dumps将一个Python数据结构转换为JSON
json.dumps用于将dict拆分成str格式,称为序列化,注意序列化后,虽然print出来仍然显示的字典的样子,但是此时已经是str类型了;
因为json.dumps序列化时对中文默认使用的是ASCII编码,如果有中文,需要执行ensure_ascii=False
a = {‘id’: ‘2203’, ‘title’: ‘title’, ‘subTitle’: ‘哈哈’}
print(type(a))
ajson = json.dumps(a)
print(ajson)
print(type(ajson))
添加ensure_ascii=False
2.json.loads将一个JSON编码的字符串转换回一个Python数据结构
a = {‘id’: ‘2203’, ‘title’: ‘title’, ‘subTitle’: ‘哈哈’}
ajson = json.dumps(a,ensure_ascii=False)
print(ajson)
print(type(ajson))
print(’------------’)
b = json.loads(ajson)
print(b)
print(type(b))
3. json.dump() 和 json.load() 来编码和解码JSON数据,用于处理文件
json.load()
def get_headers():
with open(‘headers.yaml’, ‘r’) as f:
headers = yaml.load(f, Loader=yaml.Loader) #解码JSON数据
if headers != None:
# print(headers)
return headers
else:
headers = yaml.load(f, Loader=yaml.Loader)
json.dump():
with open(‘test.json’, ‘w’) as f:
json.dump(data, f) # 编码JSON数据