python中处理json文件的方法函数

1、json.loads() 将json字符串,转变为python中的“字典”类型

import json

#json串是一个字符串
f = open('product.json',encoding='utf-8')

res=f.read()

product_dic=json.loads(res) 

print(product_dic)

运行结果:

2、json.load() 读取文件进行处理,同样是将文件中的json字符串转换为字典类型

import json

#json串是一个字符串
f = open('product.json',encoding='utf-8')

product_dic=json.load(f) 

print(product_dic)

3、json.dumps() 将字典数据转变为python中的字符串

import json

dict = {'username':'sammy'}

res=type(json.dumps(dict))

print('数据类型:%s'%res)

运行结果:

python中json.dumps(d, ensure_ascii=False, indent=4, sort_keys=True)

ensure_ascii=False 表示输出中文需要指定ensure_ascii参数为False

indent=4  表示缩进多少

sort_keys   表示是否对齐

4、json.dump() 将字典数据转变为python中的字符串,然后将其结果写入到一个文件中

import json

dict = {'username':'sammy'}

json.dump(dict,open('a.json','w',encoding='utf-8'))

运行结果:

生成一个a.json文件

 
 

猜你喜欢

转载自www.cnblogs.com/lslin/p/9033601.html