python学习(7)json库操作函数

python学习(7)json库操作函数

1.解析json字符串(json.loads)和Python对象转json(json.dumps)

#coding=utf-8
import json

strp = '[{"name": "andy", "sex": "男", "mobile": "15678904567"}, {"name": "andy2", "sex": "男", "mobile": "15678904567"}]'
#解析json
strp = json.loads(strp)
print(strp[0]['name'])
#对象解析成json
strp=json.dumps(strp)
print(strp)

输出:
andy
[{“name”: “andy”, “sex”: “\u7537”, “mobile”: “15678904567”}, {“name”: “andy2”, “sex”: “\u7537”, “mobile”: “15678904567”}]

2.写入( json.dump)和加载(json.load)json文件

#coding=utf-8
import json

strp = '[{"name": "andy", "sex": "男", "mobile": "15678904567"}, {"name": "andy2", "sex": "男", "mobile": "15678904567"}]'
#写入json文件
with open('json.txt','w') as f:
    json.dump(strp,f)
#加载json文件
with open('json.txt') as f:
  data = json.load(f)
print(data)

输出:
[{“name”: “andy”, “sex”: “\u7537”, “mobile”: “15678904567”}, {“name”: “andy2”, “sex”: “\u7537”, “mobile”: “15678904567”}]
python学习(7)json库操作函数_第1张图片

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