python 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
}
]
}
"""
1、用json.loads载入j'son格式的字符串,转成字典
import json#引用json模块
res=json.loads(s)
print(res)#打印字典
print(type(res))#打印res类型
print(res.keys())#打印字典的所有Key
2、json.load从文件中读入json格式字符串
import json
f=open('stus.json',encoding='utf-8')
user_dic=json.load(f)
print(user_dic)
3、json.dumps 将字典转成json格式字符串
stus={'xiaojun':'123456','xiaohei':'7891','abc':'11111'}

先把字典转成json

res2=json.dumps(stus)
print(res2)#打印字符串
print(type(res2))#打印res2类型
4、json.dump将字典写入json文件
stus={'xiaojun':'123456','xiaohei':'7890','lrx':'111111'}
f=open('stus2.json','w',encoding='utf-8')
json.dump(stus,f,indent=4,ensure_ascii=False)

你可能感兴趣的:(python json)