1、json支持的类型有字典和列表,整形
json必须是双引号,本身是一个字符串
2、dumps实现python类型转化为json字符串,返回一个str对象 把一个Python对象编码转换成Json字符串
dump将Python内置类型序列化为json对象后写入文件
读写记住编码与转码
import json
books = [ { 'title': '钢铁是怎样练成的', 'price': 9.8 }, { 'title': '红楼梦', 'price': 9.9 } ]
json_str = json.dumps(books,ensure_ascii=False)
with open('book.json','w',encoding='utf-8') as fp:
# fp.write(json_str)
json.dump(books,fp,ensure_ascii=False)
json.dumps()
实现python类型转化为json字符串,返回一个str对象 把一个Python对象编码转换成Json字符串
# json_dumps.py
import json
listStr = [1, 2, 3, 4]
tupleStr = (1, 2, 3, 4)
dictStr = {"city": "北京", "name": "范爷"}
json.dumps(listStr)
# '[1, 2, 3, 4]'
json.dumps(tupleStr)
# '[1, 2, 3, 4]'
# 注意:json.dumps() 序列化时默认使用的ascii编码
# 添加参数 ensure_ascii=False 禁用ascii编码,按utf-8编码
json.dumps(dictStr)
# '{"city": "\\u5317\\u4eac", "name": "\\u5927\\u5218"}'
print(json.dumps(dictStr, ensure_ascii=False))
# {"city": "北京", "name": "范爷"}
json.dump()
将Python内置类型序列化为json对象后写入文件
import json
listStr = [{"city": "北京"}, {"name": "范爷"}]
json.dump(listStr, open("listStr.json","w"), ensure_ascii=False)
dictStr = {"city": "北京", "name": "范爷"}
json.dump(dictStr, open("dictStr.json","w"), ensure_ascii=False)
3、loads把Json格式字符串解码转换成Python对象
load读取文件中json形式的字符串元素 转化成python类型
import json
book='[{"title": "钢铁是怎样练成的", "price": 9.8}, {"title": "红楼梦", "price": 9.9}]'
#必须是字符串
# TypeError: the JSON object must be str, bytes or bytearray, not list
str=json.loads(book,encoding='utf-8')
print(str) with open('book.json','r',encoding='utf-8') as fp:
# print(fp.read())
print(json.load(fp))
json.loads()
把Json格式字符串解码转换成Python对象
import json
strList = '[1, 2, 3, 4]'
strDict = '{"city": "北京", "name": "范爷"}'
json.loads(strList)
# [1, 2, 3, 4]
json.loads(strDict) # json数据自动按Unicode存储
# {u'city': u'\u5317\u4eac', u'name': u'\u5927\u732b'}
json.load()
读取文件中json形式的字符串元素 转化成python类型
import json
strList = json.load(open("listStr.json"))
print(strList)
# [{u'city': u'\u5317\u4eac'}, {u'name': u'\u5927\u5218'}]
strDict = json.load(open("dictStr.json"))
print(strDict)
# {u'city': u'\u5317\u4eac', u'name': u'\u5927\u5218'}
4 JsonPath