json通用的数据类型,所有的语言都认识
也是k-v { }
使用三个引号括起来是json,不括是字典,因为json串也是字符串
json串里都是双引号,字典都是单引号
s='''
{
"error_code": 0,
"stu_info": [
{
"id": 309,
"name": "小白",
"sex": "男",
"age": 28,
"addr": "河南省济源市北海大道32号",
"grade": "天蝎座",
"phone": "18512572946",
"gold": 100
},
{
"id": 310,
"name": "小白",
"sex": "男",
"age": 28,
"addr": "河南省济源市北海大道32号",
"grade": "天蝎座",
"phone": "18516572946",
"gold": 100
}
]
}
'''
json.loads——json转字典:
import json
res = json.loads(s) #json串(字符串),转成字典
print(res)
print(res.keys())
print(type(res))#判断类型
--------------------------------------------------------------------------------
json.dumps——字典转json:
import json
stus = {'xiaojun':'123456','xiaohei':'7891','tanailing':'11111','海龙':'111'}
res2 = json.dumps(stus,indent=8,ensure_ascii=False)
#indent加缩进,加了8个缩进,ensure_ascii=False加了这个就能显示中文了
print(res2)
with open('stus.json','w',encoding='utf-8') as f: #就可以将内容写进文件了,json文件有颜色比txt好看
f.write(res2)
--------------------------------------------------------------------------------
打开一个json文件,读出来转成字典:
import json
f = open('stus.json',encoding='utf-8')
content = f.read()
user_dic = json.loads(content) #等同于user_dic = json.loads(f.read())
print(user_dic)
简便方法json.load:
操作文件时使用load更方便,可以自动读取json文件,而loads只能读取字符串
import json
f = open('stus.json',encoding='utf-8')
user_dic = json.load(f)
print(user_dic)
--------------------------------------------------------------------------------
如果你要把字典写到文件里面,用dump:
import json
stus = {'xiaojun':'123456','xiaohei':'7891','tanailing':'11111' ,'海龙':'111'}
# res2 = json.dumps(stus,indent=8,ensure_ascii=False)
# print(res2)
# with open('stus.json','w',encoding='utf-8') as f:
# f.write(res2)
f = open('stus.json','w',encoding='utf-8')
json.dump(stus,f,indent=4,ensure_ascii=False)