4
0

More than 1 year has passed since last update.

[Python] jsonファイルが開けない…(JSONDecodeError: Extra data: line * column * (char *))

Posted at

事の発端

jsonファイルをjson.loadで開こうとしたら以下のエラーが出た。

import json
with open("sample.json") as f:
    df = json.load(f)

>>> JSONDecodeError: Extra data: line 2 column 1 (char 23)

対象のjsonファイルは以下のようになっていた。

{"id": 0, "data": 100}
{"id": 1, "data": 200}
{"id": 2, "data": 300}

json.loadで読み込むための修正

以下のようにjsonファイルを修正すると開ける。

[
  {"id": 0, "data": 100},
  {"id": 1, "data": 200},
  {"id": 2, "data": 300}
]

リストの形式にしてあげればよいということである。(最後のデータの後ろにカンマは入れてはいけない)

with open("sample.json") as f:
    df = json.load(f)

print(df)
>>> [{'id': 0, 'data': 100}, {'id': 1, 'data': 200}, {'id': 2, 'data': 300}]

jsonファイルの中身を変更しないで読み込む方法

ファイルの内容を変更すれば読み込めるとはいえ修正は面倒…という場合は以下のようにすれば読み込むことができる。

df = [json.loads(line)
        for line in open("sample.json", 'r', encoding='utf-8')]

print(df)
>>> [{'id': 0, 'data': 100}, {'id': 1, 'data': 200}, {'id': 2, 'data': 300}]

一行ずつ読み込みリストを作成するパターンですね。読み込んだ結果もファイルを修正したパターンと同じになります。

4
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
0