使用json文件读取数据

读取json文件

import json
path = "a.json"  # path为路径或者文件
with open(path,encoding="utf-8") as op:
    contents = json.load(op)

保存在json文件

import json
path = "a.json"
dict = {"name": "张三", "age": 18, "sex": "男"}
with open(path,"a",encoding="utf-8") as op:
	json.dump(dict,op,ensure_ascii=False)

转换json格式为字典格式

import json
js = '{"name": "张三", "age": 18, "sex": "男"}'
dic = json.loads(js,encoding="utf-8")
print(dic)

控制台输出

{'name': '张三', 'age': 18, 'sex': '男'}

将字典格式转换为json格式

import json
dict1 = {'name': '张三', 'age': 18, 'sex': '男'}
js1 = json.dumps(dict1,ensure_ascii=False)
print(js1)

控制台输出

{"name": "张三", "age": 18, "sex": "男"}
    原文作者:sun_8923
    原文地址: https://blog.csdn.net/sun_8923/article/details/109832660
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞