当前位置: 首页 > 图灵资讯 > 行业资讯> Python之JSON函数介绍

Python之JSON函数介绍

发布时间:2025-10-23 15:59:15

JSON函数

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

1562121277(1).png

举例说明如下:

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:

x.png

相关文章

python如何通过日志分析加入黑名单

python如何通过日志分析加入黑名单

2025-10-23
Python之JSON函数介绍

Python之JSON函数介绍

2025-10-23
python3函数

python3函数

2025-10-23
python抽象基类之_subclasshook_方法

python抽象基类之_subclasshook_方法

2025-10-22
Python3 面向对象

Python3 面向对象

2025-10-22
Python中可迭代对象、迭代器详解

Python中可迭代对象、迭代器详解

2025-10-22