{
"error_code": 0,#要使用双引号,如果是单引号则运行时会报错,可以上网做在线json格式校验
"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).load()方法
import json
res = json.loads(s)
print(res) # 打印字典
print(type(res)) #打印res类型
print(res.keys()) #打印字典的所有key
- 要先读文件,然后转换:
f = open('stus.json',encoding='utf-8')
content = f.read() #使用loads()方法需要先读文件
user_dic = json.loads(cotent)
print(user_dic)
(2).load()方法
import json
f = open('stus.json',encoding="utf-8")
user_dic = json.load(f)
print(user_dic)
(3)区别
使用loads()时需要先读取文件在使用,而load()则不用
stus = {'xiaojun':'123456','xiaohei':'7891','abc':'11111'}
res2 = json.dumps(stus) #先把字典转成json
print(res2)
print(type(res2))
with open('stus.txt','w',encoding='utf-8') as f: # 打开文件
f.write(res2) #在文件里写入转成的json串
stus={'xiaojun':'123456','xiaohei':'7890','lrx':'111111'}
res2 = json.dumps(stus,indent=8,ensuer_ascii=False)
print(res2)
with open("stus.json",'w‘,encoding='utf-8') as f # 使用.dumps()方法是要写入
f.write(res2)
(2)dump()方法
stus={'xiaojun':'123456','xiaohei':'7890','lrx':'111111'}
f = open('stus2.json','w',encoding='utf-8')
json.dump(stus,f,indent,ensure_ascii=False)
(3)区别
res2=json.dumps(stus.indent=4)
print(res2)#打印字符串
#结果为:
'''
{
"xiaojun": "123456",
"xiaohei": "7891",
"lrx": "hailong",
"tanailing": "111111"
}
'''
res2 = json.dumps(stus,indent=4,ensure_ascii=False) # 为False时内容输出显示正常的中文,而不是转码
print(res2)
原文:https://www.cnblogs.com/lpdeboke/p/11414254.html