python中json的使用

问题与背景

在python中对json的使用无非就是以下几种:

  • dict 转 json字符串
  • json字符串 转 dict
  • dict类型写入json文件
  • json文件读取为dict类型

解决方案与总结

变量类型的映射

在这里插入图片描述

dict与json互相转化

import json
tesdic = {
    'name': 'Tom',
    'age': 18,
    'score':
        {
            'math': 98,
            'chinese': 99
        }
}
print(type(tesdic))
json_str = json.dumps(tesdic)
print(json_str)
print(type(json_str))
newdic = json.loads(json_str)
print(newdic)
print(type(newdic))

输出为:

<class 'dict'>
{"name": "Tom", "age": 18, "score": {"math": 98, "chinese": 99}}
<class 'str'>
{'name': 'Tom', 'age': 18, 'score': {'math': 98, 'chinese': 99}}
<class 'dict'>

dict与json文件读写

dict写为json文件:

with open("res.json", 'w', encoding='utf-8') as fw:
    json.dump(tesdic, fw, indent=4, ensure_ascii=False)

json文件读为dict:

with open("res.json", 'r', encoding='utf-8') as fw:
    injson = json.load(fw)
print(injson)
print(type(injson))

需要注意的是,写入的时候,必须是dict形式,不能是json字符串,如果是json字符串,写完之后就会多很多转义字符,如下图:
在这里插入图片描述

参考资料

https://www.jb51.net/article/232125.htm

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值