json的读写方式与Python和字典与json的相互转化

json的读写方式与Python和字典与json的相互转化

一. python与json对象

1.json定义[python内置]

json:javascript原生的对象。(不需要第三方解析,由浏览器自动进行解析)

2.json对象的定义

jsonobj = {dict};

3.json组件的引入:import json

4.json与dict相互转换

e.g:

import json
#初始化字典
dict = {'A':1,'B':2,'C':3}
print(type(dict))#查看类型
print(dict['B'])
print(dict['C'])
#将字典对象转为json字符串:dumps(dict,ensure_ascii = False)
jsonstr = json.dumps(dict)
print(type(jsonstr))#查看类型
print(jsonstr)
#将json字符串转为字典:
jstr = jsonstr#定义json字符串
print(type(jstr))#查看类型
dict1 = json.loads(jstr,encoding='utf-8')#转为字典
print(type(dict1))#查看类型
print(dict1['A'],dict1['B'])

注:ensure_ascii = False 表示中文不用转为utf-8的字符编码

indent:多行缩进空格数

5.将dict对象转为字符串对象并存储到文件中

#with open("file_name",'w',encoding='utf-8') as f:
#   json.dump(dict_,f,indent=2,ensure_ascii=False)#写文件为多行
import json
import os
dict = {'A':1,'B':2,'C':3}

with open("file_name",'w',encoding='utf-8') as f:
    json.dump(dict,f,indent=2,ensure_ascii=False)    

6.从文件读取json字符串并转为python字典的方法

import json
import os
dict = {}
with open("filename.json",encoding='utf-8') as f:
    dict = json.load(f)
    print(dict['A'])
    print(type(dict))
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值