json文件

# # json是一个字符串
# # {"code":0,"msg":"操作成功","token":"xxxxx"}
#
#
import json
import pprint
# # 将python格式转为json格式
# dic={"code":0,"msg":"操作成功","token":"xxxxx"}
# json_str=json.dumps(dic,ensure_ascii=False) # dumps可将字典转成json串,如果内容有中文,需要加上ensure_ascii=False
# pprint.pprint(json_str)
#
# # 将json格式转为字典
# json_str='{"code":0,"msg":"操作成功","token":"xxxxx"}'
# dic=json.loads(json_str)
# pprint.pprint(dic)
#
# # 读取文件中的json内容并转为字典
# with open("result.json","r",encoding="utf-8") as f:
# dic=json.loads(f.read())
# print(dic)
# # # 方法二
#
with open("product.json","r+",encoding="utf-8") as f:
dic=json.load(f) #用load,load和dump可直接操作文件,分别可自动读、写文件,loads,dumps不可直接操作文件
print(dic)

# with open("product.json", "r", encoding="utf-8") as f:
# result = json.load(f)
# print(result)


# # # 将字典转为json串写入文件中
# dic={"code":0,"msg":"操作成功","token":"xxxxx"}
# # with open("result.json","w",encoding="utf-8") as f:
# # f.write(json.dumps(str,ensure_ascii=False,indent=4)) #indent=4可将json写入文件时,缩进4个单位
# # 方法二:
# with open("result.json","w",encoding="utf-8") as f:
# json.dump(dic,f,ensure_ascii=False,indent=4) #dump可直接操作文件,自动写入
上一篇:python字典键值对的添加和遍历


下一篇:【字节面试题】牛客刷题偶遇字节后端笔试面经 撸它