python逐行读取json_使用Python解析多行JSON文件的问题

博主在尝试使用Python2.7的json库解析包含多行的JSON文件时遇到错误。原始代码会逐行读取文件,但在删除换行符和空格后,直接尝试解析导致ValueError。通过将处理后的数据写入新文件并在读取新文件时逐行解析,问题得到解决。这表明原始文件的格式可能包含不被json库接受的换行符。
摘要由CSDN通过智能技术生成

我试图在

Python 2.7中使用json库解析JSON多行文件.简化的示例文件如下:

{

"observations": {

"notice": [

{

"copyright": "Copyright Commonwealth of Australia 2015, Bureau of Meteorology. For more information see: http://www.bom.gov.au/other/copyright.shtml http://www.bom.gov.au/other/disclaimer.shtml",

"copyright_url": "http://www.bom.gov.au/other/copyright.shtml",

"disclaimer_url": "http://www.bom.gov.au/other/disclaimer.shtml",

"feedback_url": "http://www.bom.gov.au/other/feedback"

}

]

}

}

我的代码如下:

import json

with open('test.json', 'r') as jsonFile:

for jf in jsonFile:

jf = jf.replace('\n', '')

jf = jf.strip()

weatherData = json.loads(jf)

print weatherData

不过,我收到如下错误:

Traceback (most recent call last):

File "test.py", line 8, in

weatherData = json.loads(jf)

File "/home/usr/anaconda2/lib/python2.7/json/__init__.py", line 339, in loads

return _default_decoder.decode(s)

File "/home/usr/anaconda2/lib/python2.7/json/decoder.py", line 364, in decode

obj, end = self.raw_decode(s, idx=_w(s, 0).end())

File "/home/usr/anaconda2/lib/python2.7/json/decoder.py", line 380, in raw_decode

obj, end = self.scan_once(s, idx)

ValueError: Expecting object: line 1 column 1 (char 0)

为了做一些测试,我修改了代码,以便在删除换行符并去掉前导和尾随空格后,将内容写入另一个文件(带有json扩展名).令人惊讶的是,当我读回后一个文件时,我没有收到任何错误,解析成功.修改后的代码如下:

import json

filewrite = open('out.json', 'w+')

with open('test.json', 'r') as jsonFile:

for jf in jsonFile:

jf = jf.replace('\n', '')

jf = jf.strip()

filewrite.write(jf)

filewrite.close()

with open('out.json', 'r') as newJsonFile:

for line in newJsonFile:

weatherData = json.loads(line)

print weatherData

输出如下:

{u'observations': {u'notice': [{u'copyright_url': u'http://www.bom.gov.au/other/copyright.shtml', u'disclaimer_url': u'http://www.bom.gov.au/other/disclaimer.shtml', u'copyright': u'Copyright Commonwealth of Australia 2015, Bureau of Meteorology. For more information see: http://www.bom.gov.au/other/copyright.shtml http://www.bom.gov.au/other/disclaimer.shtml', u'feedback_url': u'http://www.bom.gov.au/other/feedback'}]}}

在使用json库之前删除新行和空格时可能会发生什么?

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值