Python 2.7でjson
ライブラリを使用してJSON複数行ファイルを解析しようとしています。単純化されたサンプルファイルは以下の通りである:次のようにPythonを使用して複数行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
)に内容を書き込むようにコードを修正しました。驚いたことに、私が後者のファイルを読み返すと、私は何のエラーも得られず、解析は成功です。 json
ライブラリを使用する前に取り除かれたときに、新しいラインと白のスペースに行くかもしれないもの
{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'}]}}
任意のアイデアを次のように
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
出力は次のとおりです。次のように変更されたコードはありますか?
ありがとう@OkezieE。 'load'を介してファイル全体をロードすることは、そのトリックを行います。 – hypersonics