指点成金-最美分享吧

登录

json与字典相互转换

佚名 举报

篇首语:本文由小编为大家整理,主要介绍了json与字典相互转换相关的知识,希望对你有一定的参考价值。

1.将字典转成json

import json

dic = "name":"wangyujian","sex":"男","age":18

js = json.dumps(dic,ensure_ascii=False)   # ensure_ascii=False 将字典中的中文编码转换一下,不然输出时显示的是ASCII码

print(js)

 

2.将字典转成json并存放在文件中

import json

dic = "name":"wangyujian","sex":"男","age":18

js = open("a.json","w",encoding="utf-8")

json.dump(dic,js,ensure_ascii=False,indent=4)  # indent代表首行缩进多少行

 

3.将json转成字典

import json

js = ""name":"wangyujian","sex":"男","age":18"

dic = json.loads(js)

print(dic)

 

4.从文件中读取json,并转化成字典

import json

js = open("a.json","r",enconding="utf-8")

dic = json.load(js)

print(dic)

 

以上是关于json与字典相互转换的主要内容,如果未能解决你的问题,请参考以下文章