回答此问题可获得 20 贡献值,回答如果被采纳可获得 50 分。
<p>我试图使用Python 2.7中的<code>json</code>库解析JSON多行文件。下面给出了一个简化的示例文件:</p>
<pre><code>{
"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"
}
]
}
}
</code></pre>
<p>我的代码如下:</p>
<pre><code>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
</code></pre>
<p>但是,我得到一个错误,如下所示:</p>
<pre><code>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)
</code></pre>
<p>为了进行一些测试,我修改了代码,以便在删除换行符并去掉前导和尾随空格之后,将内容写入另一个文件(扩展名为<code>json</code>)。令人惊讶的是,当我读回后一个文件时,我没有得到任何错误,并且解析成功。修改后的代码如下:</p>
<pre><code>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
</code></pre>
<p>输出如下:</p>
<pre><code>{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'}]}}
</code></pre>
<p>知道在使用<code>json</code>库之前删除新行和空白会发生什么吗?</p>