python之json字典基础处理

原文链接: http://www.cnblogs.com/chen-xia/articles/10882073.html
#!/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

猜你喜欢

转载自blog.csdn.net/weixin_30279315/article/details/94871942
今日推荐