json是JavaScript对象表示法的缩写,是一种轻量级的数据交换格式,经常被用于Web应用程序中。python中的json库是用于解析和生成json数据格式的库。
import jsondata = {"name": "张三","age": 18,"hobbies": ["reading", "music"],"info": {"address": "北京市朝阳区","phone": "18888888888"}
}#json.dumps()是用于将python对象序列化为json编码字符串
#ensure_ascii保证每个字符都是ASCII字符
# indent 用于控制缩进的参数
json_str = json.dumps(data, ensure_ascii=False, indent=1)print(json_str)# json.loads() 用于将json字符串解码为python对象
data=json.loads(json_str)
print(type(data))
print(data)
import json# 将json数据写入到文件中
data = {"name": "王五","age": 30,"hobbies": ["travelling", "photography"],"info": {"address": "广州市天河区","phone": "13666666666"}
}
with open('data.json', 'w') as f:json.dump(data, f, ensure_ascii=False, indent=4)# 从文件中读取json数据
with open('data.json', 'r') as f:data = json.load(f)print(type(data))print(data)