Python之JSON函数介绍

Python (198) 2023-04-17 16:36:37

JSON函数

使用 JSON 函数需要导入 json 库:import json。

举例说明,如下:

a.json内容格式:

{"car":{"price":1100,"color":"red"},"mac":{"price":7999,"color":"black"},"abc":{"price":122,"color":"green"}}

json.load()

importjson
withopen('a.json')asfp:
shop_dic=json.load(fp)#从a.json文件内读取数据,返回结果为字典:{'abc':{'price':122,'color':'green'},
'mac':{'price':7999,'color':'black'},'car':{'price':1100,'color':'red'}}
print(shop_dic)

json.loads()

s_json='{"name":"niuniu","age":20,"status":true}'
print(json.loads(s_json))#将json串转换为字典:{'age':20,'status':True,'name':'niuniu'}

相关推荐:《Python视频教程》

json.dump()

importjson
withopen('a.json','a+')asfp:
dic={'name':'niuniu','age':18}
fp.seek(0)
fp.truncate()
json.dump(dic,fp)#将字典转换为json串写入文件

写入的a.json如下:

{"age":18,"name":"niuniu"}
json.dumps()
importjson
dic={'name':'niuniu','age':18}
print(json.dumps(dic))#将字典转换为json串:{"name":"niuniu","age"

扩展小知识点:

将字典内容写入json文件,包含中文。

1. 中文写入json文件后显示乱码,怎么解决? ensure_ascii = False

2. 写入的字典内容显示为不一行,显示不美观,怎么解决? indent = 4

importjson
d={"Name":"战神","sex":["男","女","人妖"],"Education":{"GradeSchool":"第一小学",
"MiddleSchool":["第一初中","第一高中"],"University":{"Name":"哈佛大学","Specialty":["一年级","二年级"]}}}
withopen('a.json','w',encoding='utf-8')asf:
#中文显示乱码问题,ensure_ascii=False
#json格式化问题,indent=8
#s=json.dumps(d,ensure_ascii=False,indent=8)字典转换为json字符串
#f.write(s)

#第二种写法
json.dump(d,f,ensure_ascii=False,indent=8)

写入的json文件,a.json:

THE END

发表回复