json字符串格式读写操作

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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值