Python处理JSON
背景
拖了很久的项目,有一个大概是爬虫爬来的文档,全是JSON格式的,为了能够进一步处理,需要把里面的东西扒出来,大概了解了一下基本主要的语言都有JSON读写库,刚好这个项目要用Python,就用了Python来做这件事,Python中的字典一类的原生数据结构刚好对应JSON的格式,因而库也比较简单。
文件读入
Python文件读入很简单
file = open("xxx.xxx", 'r', encoding = 'utf-8')
第一个参数是文件名,第二个是模式,’r’是读入,’w’是输出,第三个是编码,编码没有指定或者指定错误会出现
UnicodeDecodeError: 'gbk' codec can't decode byte 0x9d in position 1060: illegal multibyte sequence
JSON解码
引入json库
import json
json.dumps()编码
json.loads()解码
decodejson = json.loads(encodedjson)
print decodejson
Python3中字符串类型错误
TypeError: 'str' does not support the buffer interface
从JSON中解出的’str’类型(?JSON中string对应似乎是unicode类型)可以print,但写入文件时会提示
TypeError: 'str' does not support the buffer interface
str类型要编成utf-8类型
str.encode('utf-8')
代码
import json
file = open("gms_small.dat", 'r', encoding = 'utf-8')
res = open("res.txt", 'wb')
for line in file.readlines():
decodejson = json.loads(line)
id = decodejson['_id']['$oid']
main = decodejson['mainStory']
res.write(id.encode('utf-8'))
res.write('\n'.encode('utf-8'))
res.write(main.encode('utf-8'))
res.write('\n\n'.encode('utf-8'))
file.close()
res.close()