gpt4 book ai didi

python - 使用 Python 问题解析多行 JSON 文件

转载 作者:太空狗 更新时间:2023-10-30 00:31:38 24 4
gpt4 key购买 nike

我正在尝试使用 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 <module>
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 库之前去除新行和空格会发生什么吗?

最佳答案

如果您尝试逐行解析 json 文件,您将会发疯。 json 模块具有直接读取文件对象或字符串的辅助方法,即 loadloads 方法。 load 为包含 json 数据的文件获取文件对象(如下所示),而 loads 获取包含 json 数据的字符串。

选项 1:- 首选

import json
with open('test.json', 'r') as jf:
weatherData = json.load(jf)
print weatherData

选项 2:

import json
with open('test.json', 'r') as jf:
weatherData = json.loads(jf.read())
print weatherData

如果您正在寻找更高性能的 json 解析,请查看 ujson

关于python - 使用 Python 问题解析多行 JSON 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34461917/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com