python之json字典基础处理

#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
json.dumps()和json.loads()是json格式处理函数(json.dumps()是把字典类型格式化json对象,json.loads()把json对象转成字典)
json.dump()和json.load()是json文件处理(json.load()用于读取文件,json.dump()用于写文件)
'''

import json
#———————————把字典转成json字符串——————————————
dic1 = {'type':'dic1','username':'loleina','age':16,'chen':'湖北省广水市关庙镇','所属国家':'宇宙安全局'}
#json_dic1 = json.dumps(dic1)#不能打印中文(json.dumps默认是ascii码)
json_dic1=json.dumps(dic1, ensure_ascii=False)#可打印中文
print (json_dic1)

#——————————字典格式化_显示json对象数据格式——————————————————
json_dic2 = json.dumps(dic1,sort_keys=True,indent =4,separators=(',', ': '),ensure_ascii=False)#ensure_ascii表示是否使用asciii编码
print (json_dic2)

#————————把json对象格式写入文件(保存格式为json字符串)————————————————
with open('casedate.json', 'w', encoding='utf-8') as f:#写文件
  json.dump(json_dic2, f, sort_keys=True, ensure_ascii=False,indent=4)#ensure_ascii表示编码

#——————————把字典写入到文件(保存为json对象格式)———————————————————————
chenchen = {'type':'dic1','username':'loleina','age':16,'chen':'湖北省广水市关庙镇','所属国家':'宇宙安全局'}
with open('chenwei.json', 'w', encoding='utf-8') as f:#写文件
  json.dump(chenchen, f, sort_keys=True, ensure_ascii=False,indent=4)#ensure_ascii表示编码

#————————————把json字符串转成字典__然后再转成json对象格式—————————————————
aa="{\n    \"age\": 16,\n    \"chen\": \"湖北省广水市关庙镇\",\n    \"type\": \"dic1\",\n    \"username\": \"loleina\",\n    \"所属国家\": \"宇宙安全局\"\n}"
bb=json.loads(aa)#转为字典格式
print(bb)
#转成json对象格式
cc = json.dumps(bb,sort_keys=True,indent =4,separators=(',', ': '),ensure_ascii=False)#ensure_ascii表示是否使用asciii编码
print(cc)
#-----------------------------从文件中读取数据------------------------------------------------------
#第一种方法,从文件读取json数据
file = open('chenwei.json','r',encoding='utf-8')
info = json.load(file)#直接读取文件,不需要file.read()
print(info)

#第二种方法(写完文件自动关闭)    
with open('chenwei.json','r', encoding='utf-8') as f:
    cc=f.read()
k=json.loads(cc)#把json格式转为字典
print(k)

 

转载于:https://www.cnblogs.com/chen-xia/articles/10882073.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值