Python处理JSON

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()

参考

廖雪峰Python3教程

Json概述以及python对json的相关操作

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值