首页 > 编程语言 > 详细

python-json处理

时间:2018-01-20 00:12:56      阅读:247      评论:0      收藏:0      [点我收藏+]

1、json 串就是字符串

2、需要提前引入, 即import

3、将list /字典等 转化为json数据类型:json.dumps()

#json.dumps(d)       #把list\字典转为json
#json.dumps(d,indent=8) #把list\字典转为json, indent 缩进
#json.dumps(d,indent=8,ensure_ascii=False) #可以显示这中文
import json
d={‘car‘:{‘color‘:‘red‘,‘price‘:‘1000‘,‘count‘:30},
‘phone‘: {‘color‘: ‘red‘, ‘price‘: ‘1000‘, ‘count‘: 30},
‘pen‘: {‘color‘: ‘red‘, ‘price‘: ‘1000‘, ‘count‘: 30},
‘flower‘: {‘color‘: ‘red‘, ‘price‘: ‘1000‘, ‘count‘: 30},
‘手机‘: {‘color‘: ‘yel‘, ‘price‘: ‘1000‘, ‘count‘: 30}
}
#res=json.dumps(d) #把list\字典转为json
#res=json.dumps(d,indent=8) #把list\字典转为json, indent 缩进
res=json.dumps(d,indent=8,ensure_ascii=False) #可以显示这中文
print(res)
print(type(res))

4、将json数据类型python 类型(字典或list):json.loads()

json 数据串 必须为双引号, 不能为单引号,否则程序报错

f1=open(‘f1‘,‘r‘,encoding=‘utf-8‘)
res=f1.read()
dict_res=json.loads(res)#将json串 转化为字典 或者 list, 根据json 串的格式
print(dict_res)
print(type(dict_res))

5、json 自动与文件操作: 

json.dump(d,f1,ensure_ascii=False,indent=4)         #dump  操作文件,即将信息自动写入文件,第一个参数为数据, 第二个为文件对象
#例如
#f1=open(‘f1‘,‘w‘,encoding=‘utf-8‘)
# json.dump(d,f1,ensure_ascii=False,indent=4) #dump 操作文件,即将信息自动写入文件,第一个参数为数据, 第二个为文件对象
# json.load()

json.load(f1)       #直接传入文件对象,会自动 读取

#例如
f1=open(‘f1‘,encoding=‘utf-8‘)
print(json.load(f1))
    

6、

7、

 

 

 





 

python-json处理

原文:https://www.cnblogs.com/jyjcode/p/8282691.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!