python3 json的读取与存储

1.python读取.json格式文件到dict中

简单来说:
读取json文件需要用json.load转码,保存字典文件为json格式需要用json.dump转码

数据文件:student.json

{"name": "张三", "age": 13}
{"name": "李四", "age": 14}

读取上述文件并保存在字典中,如果直接读取

# -*- coding: utf-8 -*-
import json
import codecs

data = []
with codecs.open("student.json", "r", "utf-8") as f:
    for line in f:
        #dic = json.loads(line)
        dic = line
        data.append(dic)
        print (json.dumps(dic, indent=4, ensure_ascii=False))

结果
在这里插入图片描述
都出来的json为字符串(str)类型,用json.load转成dict类型

# -*- coding: utf-8 -*-
import json
import codecs

data = []
with codecs.open("student.json", "r", "utf-8") as f:
    for line in f:
        #dic = json.loads(line)
        dic = line
        data.append(dic)
        print (json.dumps(dic, indent=4, ensure_ascii=False))

结果
在这里插入图片描述

如果还是
在这里插入图片描述
可以先f.readlines()在json.loads

import json
import codecs

data = []
with codecs.open(r"student.json", "r", "utf-8") as f:
    data1 = f.readlines()
    for line in data1:
        dic = json.loads(line)
        data.append(dic)
        print (json.dumps(dic, indent=4, ensure_ascii=False))
 

2. python存储dict()为.json格式文件

dic = {'name': '张三', 'age': '13'}

with codecs.open('student.json','a', 'utf-8') as outf:
    json.dump(dic, outf, ensure_ascii=False)
    outf.write('\n')

如果是从json读入dict,在写入json,请读入时使用json.loads(), 写入时先经过json.dump()

3.在使用json.dumps时注意中文的问题

import json
print (json.dumps('西安交通大学'))
#output: "\u897f\u5b89\u4ea4\u901a\u5927\u5b66"

输出的是“西安交通大学”的ascii字符码,而不是真正的中文。这是因为json.dumps 序列化时对中文默认使用的ascii编码.想输出真正的中文需要指定ensure_ascii=False:而英文字符则不存在这一点。

import json
print (json.dumps('西安交通大学',ensure_ascii=False))
#output:"西安交通大学"
print (json.dumps('AAAI'))
#output:"AAAI"

更进一步,可以自己指定encoding,默认encoding=‘utf-8’

import json
print (json.dumps('西安交通大学',ensure_ascii=False,encoding='utf-8'))
#output:"西安交通大学"

4 .Python3 中codecs进行文件的读取

参考Python3 中codecs进行文件的读取,以下为ccorz所写:

简单的概念与说明

编码(动词):按照某种规则(这个规则称为:编码(名词))将“文本”转换为“字节流”。而在python 3中则表示:unicode变成str

解码(动词):将“字节流”按照某种规则转换成“文本”。而在python3中则表示:str变成unicode

Python中编码、解码与Unicode的联系

字符串在Python内部的表示是Unicode编码,因此,在做编码转换时,通常需要以Unicode作为中间编码,即先将其他编码的字符串解码(decode)成Unicode,再从Unicode编码(encode)成另一种编码。

在新版本的python3中,取消了unicode类型,代替它的是使用unicode字符的字符串类型(str),字符串类型(str)成为基础类型如下所示,而编码后的变为了字节类型(bytes)但是两个函数的使用方法不变:

      decode              encode
bytes ------> str(unicode)------>bytes
u = '中文' #指定字符串类型对象u 
str = u.encode('gb2312') #以gb2312编码对u进行编码,获得bytes类型对象str 
u1 = str.decode('gb2312')#以gb2312编码对字符串str进行解码,获得字符串类型对象u1 
u2 = str.decode('utf-8')#如果以utf-8的编码对str进行解码得到的结果,将无法还原原来的字符串内容

避免不了的是,文件读取问题:

假如我们读取一个文件,文件保存时,使用的编码格式,决定了我们从文件读取的内容的编码格式,例如,我们从记事本新建一个文本文件test.txt, 编辑内容,保存的时候注意,编码格式是可以选择的,例如我们可以选择gb2312,那么使用python读取文件内容,方式如下:

f = open('test.txt','r')
s = f.read() #读取文件内容,如果是不识别的encoding格式(识别的encoding类型跟使用的系统有关),这里将读取失败

‘’‘假设文件保存时以gb2312编码保存’’’
u = s.decode(‘gb2312’) #以文件保存格式对内容进行解码,获得unicode字符串

‘’‘下面我们就可以对内容进行各种编码的转换了’’’
str = u.encode(‘utf-8’)#转换为utf-8编码的字符串str
str1 = u.encode(‘gbk’)#转换为gbk编码的字符串str1
str1 = u.encode(‘utf-16’)#转换为utf-16编码的字符串str1

codecs进行文件的读取

python给我们提供了一个包codecs进行文件的读取,这个包中的open()函数可以指定编码的类型:

import codecs 
f = codecs.open('text.text','r+',encoding='utf-8')#必须事先知道文件的编码格式,这里文件编码是使用的utf-8 
content = f.read()#如果open时使用的encoding和文件本身的encoding不一致的话,那么这里将将会产生错误 
f.write('你想要写入的信息') 
f.close()

参考:

  1. https://stackoverflow.com/questions/956867/how-to-get-string-objects-instead-of-unicode-from-json
  2. https://www.jianshu.com/p/90ecc5987a18
  3. https://www.cnblogs.com/ccorz/p/6089322.html
  4. https://www.jianshu.com/p/86d66257de41
  5. https://blog.csdn.net/qq_23926575/article/details/76566209
  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值