python-json

#json是通用的数据类型,所有语言都认识
#key-value
#
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
}
]
}
'''
import json
res = json.loads(s)#json转换成字典
print(res)
print(res.keys())
print(type(res))

stus = {'张三':'123456','李四':'123456','wangwu':'123456'}
res2 = json.dumps(stus,indent=8,ensure_ascii=False)#字典转换成字符串
#indent=8,json格式
#ensure_ascii=False中文可以正常显示
print(res2)
print(type(res2))
with open('file.json','w',encoding='utf-8') as f3:
f3.write(res2)

-----------------------------------------------------------------------------------------------------------

import json
# f = open('file.json',encoding='utf-8')
# content = f.read()
# user_dic = json.loads(content) #转换成字典
# print(user_dic)
#loads和load区别,loads传字符串,load传文件对象
# f = open('file.json',encoding='utf-8')
# user_dic = json.load(f) #转换成f字典
# print(user_dic)


stus = {'张三':'123456','李四':'123456','wangwu':'123456'}



with open('file.json','w',encoding='utf-8') as f3:
res2 = json.dump(stus,f3, indent=4, ensure_ascii=False) # 字典转换成字符串
# indent=4,json格式
# ensure_ascii=False中文可以正常显示

#如果要把字典写到文件里面的,dump比dumps要好用
posted @ 2018-09-07 00:28  白兰鸽05  阅读(131)  评论(0编辑  收藏  举报