PythonでJSONを読み込み・書き込みする方法|\uになる・エラーの直し方

  • Web API から取ったデータを JSON で保存して、あとで読み直して使いたい
  • json.dump で保存すると、日本語が \u5c71 のような文字になる
  • datetime を入れると TypeError、読み込むと JSONDecodeError で止まる

このような悩みにお答えします。

Python で JSON を扱うなら、標準ライブラリの json モジュールで足ります。標準ライブラリとは、Python に最初から付いていて、インストールしなくても使える部品のことです。

JSON(JavaScript Object Notation)は、{"id": 1001} のように、名前と値の組をテキストで書く形式です。Web API の応答や設定ファイルでよく使われます。

書くときはファイルを encoding="utf-8" で開き、json.dump() に ensure_ascii=False と indent=2 を付けると、日本語のまま読みやすい形で保存できます。

まず何をすればよいか
  1. 書く:open(パス, "w", encoding="utf-8") で開き、json.dump(data, f, ensure_ascii=False, indent=2)
  2. 読む:open(パス, encoding="utf-8") で開き、json.load(f)
  3. 止まったら:TypeError は default= で文字列に変える。JSONDecodeError はメッセージの行と列を見る

この記事では、Web API から取った注文のデータを保存し、あとで読み直して集計する流れを例に、次のことを実際に動かして確かめます。

  • dump・load・dumps・loads の4つの関数の違いと使い分け
  • 日本語が \u になる理由と、ensure_ascii=False・indent・encoding の付け方
  • datetime・Decimal・set を保存する方法(default=)と、読むときに元の型へ戻す方法
  • JSONDecodeError の原因の切り分け(空のファイル・BOM・末尾のカンマ・シングルクォート・途中で切れた)
  • 書きかけのファイルを残さない保存のしかたと、追記に向いた JSON Lines
項目内容
OSmacOS 27.2.1
Python3.12.16(json は Python に付いている標準ライブラリ)
Web API外への通信はせず、手元のファイルを API の応答の代わりに使う
Windows未確認(文字コードとファイルの入れ替えの節で、Windows の動きを書いたところ)
この記事の環境(2026年12月5日に確認)

この記事のコードの出力は、すべて僕が上の環境で実際に動かした結果です。外への通信はしていないので、Web API の応答は手元のファイルで代わりにしています。

Python で Excel・Outlook・Web API などの仕事を自動化する全体の流れと、ライブラリの選び方はこちらにまとめています。

目次
  1. JSONの読み書きは4つの関数:ファイルはdump・load、文字列はdumps・loads
  2. Web APIの応答をJSONファイルに保存する:ensure_ascii=False・indent・encodingを付ける
  3. 保存したJSONを読み込んで使う:json.loadで辞書とリストに戻る
  4. datetime・Decimal・setを保存する:default=で文字列にし、読むときに戻す
  5. JSONDecodeErrorの切り分け:メッセージの行と列から原因を探す
  6. 大きなデータや追記にはJSON Lines:1行に1件のJSONを書く
  7. サンプルコードで全体像を掴む:取得→保存→読み直しを1つにまとめる
  8. よくある質問
  9. まとめ:encoding=”utf-8″で開き、ensure_ascii=Falseで書き、エラーは行と列を見る

JSONの読み書きは4つの関数:ファイルはdump・load、文字列はdumps・loads

json モジュールで使う関数は、ほぼ4つです。ファイルとやり取りするなら dump・load、文字列とやり取りするなら、名前の最後に s が付いた dumps・loads を使います。

JSONとPythonの値の対応

JSON を読み込むと、Python の辞書・リスト・文字列・数などに変わります。どの値が何になるかを、1つの JSON で確かめました。

Python
import json

text = '{"name": "山田", "age": 30, "height": 171.5, "tags": ["a", "b"], "admin": false, "memo": null}'
data = json.loads(text)

for key, value in data.items():
    print(f"{key:7}: {value!r:12} {type(value).__name__}")
ShellScript
python 01_types.py
Plaintext
name   : '山田'         str
age    : 30           int
height : 171.5        float
tags   : ['a', 'b']   list
admin  : False        bool
memo   : None         NoneType

対応をまとめると、次の表のとおりです。書くときは、この逆の向きに変わります。

JSONPython例
オブジェクト {}辞書 dict{"name": "山田"}
配列 []リスト list["a", "b"]
文字列str"山田"
数int・float30・171.5
true・falseTrue・False頭が小文字になる
nullNone値がないことを表す
JSON と Python の値の対応

JSON には日付や時刻の型がありません。datetime を保存するときの書き方は、あとの節で説明します。

dumpsとdumpの違い(4つの関数の早見表)

dumps は JSON の文字列を返し、dump はファイルに書きます。読むほうも同じで、loads は文字列から、load はファイルから読みます。

関数何から何へ使う場面
json.dump(data, f)Python の値 → ファイルJSON ファイルに保存する
json.load(f)ファイル → Python の値JSON ファイルを読み込む
json.dumps(data)Python の値 → 文字列画面に表示する・API に送る文字を作る
json.loads(text)文字列(bytes も可)→ Python の値API の応答を読む
json モジュールの4つの関数

s は string(文字列)の s と覚えると、取り違えにくくなります。4つを1回ずつ使ってみます。

Python
import json

data = {"id": 1001, "customer": "山田 太郎"}

# 文字列とのやり取り:dumps・loads(s は string の s)
text = json.dumps(data, ensure_ascii=False)
print("dumps :", type(text).__name__, text)
print("loads :", json.loads(text))

# ファイルとのやり取り:dump・load
with open("one.json", "w", encoding="utf-8") as f:
    json.dump(data, f, ensure_ascii=False)
with open("one.json", encoding="utf-8") as f:
    print("load  :", json.load(f))
ShellScript
python 02_four.py
Plaintext
dumps : str {"id": 1001, "customer": "山田 太郎"}
loads : {'id': 1001, 'customer': '山田 太郎'}
load  : {'id': 1001, 'customer': '山田 太郎'}

dumps の結果は str(文字列)です。ファイルの dump と load も、同じ辞書を書いて読み戻せています。

dumpとloadで間違えやすい渡し方

dump と load には、ファイル名ではなく、open() で開いたファイルを渡します。取り違えたときのエラーを並べました。

Python
import json

data = {"id": 1001}

# dump にファイルを渡し忘れる
try:
    json.dump(data)
except TypeError as e:
    print("dump(data)       ->", type(e).__name__, e)

# load にファイル名(文字列)を渡す
try:
    json.load("one.json")
except AttributeError as e:
    print("load('one.json') ->", type(e).__name__, e)

# loads にファイル名を渡す(ファイル名そのものを JSON として読もうとする)
try:
    json.loads("one.json")
except json.JSONDecodeError as e:
    print("loads('one.json')->", type(e).__name__, e)
ShellScript
python 03_mixup.py
Plaintext
dump(data)       -> TypeError dump() missing 1 required positional argument: 'fp'
load('one.json') -> AttributeError 'str' object has no attribute 'read'
loads('one.json')-> JSONDecodeError Expecting value: line 1 column 1 (char 0)

json.load("one.json") は、文字列には read がない、という AttributeError になります。

json.loads("one.json") は、ファイル名そのものを JSON として読もうとして JSONDecodeError になります。

どちらもファイルの中身は見ていません。ファイルから読むときは with open(...) as f: で開いて json.load(f) です。

Web APIの応答をJSONファイルに保存する:ensure_ascii=False・indent・encodingを付ける

Web API の応答は、json.loads() で辞書にしてから json.dump() でファイルに書きます。ensure_ascii=False で日本語を残し、indent=2 で読める形にし、encoding="utf-8" で開きます。

例で使うWeb APIの応答

この記事では外へ通信しないため、Web API の代わりに、次の fake_api.py を使います。api フォルダの orders.json を、通信したときと同じ bytes(バイト列。文字にする前の生のデータ)で返すだけの関数です。

Python
"""Web API の代わり:手元の api フォルダにある応答を、通信したときと同じ bytes で返す"""
from pathlib import Path

API_DIR = Path(__file__).parent / "api"


def get(name):
    # 本物の API なら urllib.request.urlopen(URL).read() や requests.get(URL).content
    return (API_DIR / f"{name}.json").read_bytes()

返す中身は、次の注文の一覧です。API の応答によくある形で、改行のない1行の JSON にしてあります。

JSON
{"date":"2026-12-05","orders":[{"id":1001,"customer":"山田 太郎","items":["ノート","ペン"],"amount":1200,"paid":true,"coupon":null},{"id":1002,"customer":"佐藤 花子","items":["ファイル"],"amount":450,"paid":false,"coupon":"WINTER"},{"id":1003,"customer":"鈴木 一郎","items":["付箋","ノート","はさみ"],"amount":2380,"paid":true,"coupon":null}]}

本物の API なら、get() の中を urllib.request.urlopen(URL).read() に替えると、同じ bytes が手に入ります。

json.loadsで応答を辞書にする

API の応答は、json.loads() に渡すと辞書になります。loads は文字列だけでなく、bytes もそのまま受け取れます。

Python
import json

import fake_api

body = fake_api.get("orders")  # Web API の応答(bytes)
print(type(body).__name__, len(body), "バイト")

data = json.loads(body)  # bytes のまま渡せる
print(type(data).__name__, list(data.keys()))
print(data["orders"][0]["customer"], data["orders"][0]["amount"])
ShellScript
python 04_fetch.py
Plaintext
bytes 373 バイト
dict ['date', 'orders']
山田 太郎 1200

373 バイトの bytes が、date と orders を持つ辞書になりました。data["orders"][0]["customer"] のように、キーと番号をたどって値を取り出します。

requests を使う場合は、requests.get(URL).json() で同じように辞書が返ります。通信のしかた(ヘッダー・パラメーター・POST)は、requests の記事にまとめています。

そのままdumpすると日本語が\uになる

取り出した辞書を、何も指定せずに json.dump() で保存してみます。

Python
import json

import fake_api

data = json.loads(fake_api.get("orders"))

with open("orders_default.json", "w", encoding="utf-8") as f:
    json.dump(data, f)  # 何も指定しない

with open("orders_default.json", encoding="utf-8") as f:
    text = f.read()
print(text[:text.index('"items"')] + "…")  # 1件目の名前のところまで表示

with open("orders_default.json", encoding="utf-8") as f:
    print(json.load(f)["orders"][0]["customer"])  # 読み直すと元に戻る
ShellScript
python 05_save_default.py
Plaintext
{"date": "2026-12-05", "orders": [{"id": 1001, "customer": "\u5c71\u7530 \u592a\u90ce", …
山田 太郎

「山田 太郎」が \u5c71\u7530 \u592a\u90ce になりました。

json.dump() は、何も指定しないと日本語などの ASCII(英数字と記号)以外の文字を、\u と16進数の番号に置き換えて書きます。この置き換えを決めているのが ensure_ascii(初期値は True)です。

壊れたわけではないので、出力の2行目のとおり、json.load() で読み直すと「山田 太郎」に戻ります。ただ、ファイルを開いて目で確かめるには不便です。

ensure_ascii=Falseとindent=2で読める形にする

ensure_ascii=False を付けると、日本語がそのまま書かれます。indent=2 を付けると、入れ子ごとに2文字ずつ下げて改行します。

次の例では、data フォルダに日付入りの名前で保存します。

Python
import json
from pathlib import Path

import fake_api

data = json.loads(fake_api.get("orders"))

out_dir = Path("data")
out_dir.mkdir(exist_ok=True)
path = out_dir / f"orders_{data['date']}.json"

with open(path, "w", encoding="utf-8") as f:
    json.dump(data, f, ensure_ascii=False, indent=2)

lines = path.read_text(encoding="utf-8").splitlines()
print(f"{path}({len(lines)} 行。最初の16行を表示)")
print("\n".join(lines[:16]))
ShellScript
python 06_save.py
Plaintext
data/orders_2026-12-05.json(38 行。最初の16行を表示)
{
  "date": "2026-12-05",
  "orders": [
    {
      "id": 1001,
      "customer": "山田 太郎",
      "items": [
        "ノート",
        "ペン"
      ],
      "amount": 1200,
      "paid": true,
      "coupon": null
    },
    {
      "id": 1002,

1行だった応答が、38行の読みやすい形になりました。true・null も JSON の書き方のまま保存されています。

Path("data").mkdir(exist_ok=True) は、data フォルダがなければ作り、あれば何もしない書き方です。フォルダの作り方やパスの組み立て方は、pathlib の記事で紹介しています。

open()にencoding=”utf-8″を付ける

ensure_ascii=False で書くときは、open() に encoding="utf-8" を必ず付けます。日本語がそのままファイルに書かれるので、ファイルの文字コード(文字をバイトに置き換える決まり)が効いてくるためです。

Python 3.12 の open() は、encoding を付けないと OS の設定の文字コードを使います。日本語の Windows では cp932(Shift_JIS を広げたもの)になることが多く、cp932 にない文字は書けません。

僕の Mac では指定しなければ UTF-8 になるので、encoding="cp932" をわざと付けて、同じことを起こしました。

Python
import json

data = {"customer": "𠮷田 一郎"}  # 「𠮷」は cp932 にない文字

# Windows で encoding を付けずに開いたときと同じ cp932 を、わざと指定して試す
for ensure_ascii in (True, False):
    try:
        with open("cp932.json", "w", encoding="cp932") as f:
            json.dump(data, f, ensure_ascii=ensure_ascii)
        with open("cp932.json", encoding="cp932") as f:
            print(f"ensure_ascii={ensure_ascii!s:5} -> 書けた: {f.read()}")
    except UnicodeEncodeError as e:
        print(f"ensure_ascii={ensure_ascii!s:5} -> UnicodeEncodeError: {e.reason} {e.object[e.start]!r}")

with open("utf8.json", "w", encoding="utf-8") as f:
    json.dump(data, f, ensure_ascii=False)
with open("utf8.json", encoding="utf-8") as f:
    print("encoding='utf-8'   -> 書けた:", f.read())
ShellScript
python 07_encoding.py
Plaintext
ensure_ascii=True  -> 書けた: {"customer": "\ud842\udfb7\u7530 \u4e00\u90ce"}
ensure_ascii=False -> UnicodeEncodeError: illegal multibyte sequence '𠮷'
encoding='utf-8'   -> 書けた: {"customer": "𠮷田 一郎"}

ensure_ascii=False で cp932 に書くと、「𠮷」(つちよし)で UnicodeEncodeError になりました。ensure_ascii=True のままなら日本語は \u に置き換わるので書けますが、人が目で読めない形に戻ってしまいます。

encoding="utf-8" なら、「𠮷」もそのまま書けました。Windows で encoding を付けずに開いたときの動きは、Windows で未確認です。どの環境でも encoding="utf-8" を付けておけば迷いません。

保存したJSONを読み込んで使う:json.loadで辞書とリストに戻る

保存した JSON ファイルは、encoding="utf-8" で開いて json.load() に渡すと、保存する前と同じ辞書とリストに戻ります。あとは、ふつうの辞書と同じように使えます。

json.loadで読み込んで集計する

上で保存した data/orders_2026-12-05.json を読み込み、注文を1件ずつ表示して、金額を合計します。

Python
import json

with open("data/orders_2026-12-05.json", encoding="utf-8") as f:
    data = json.load(f)

total = 0
for order in data["orders"]:
    mark = "済" if order["paid"] else "未"
    print(f"{order['id']} {order['customer']} {order['amount']:>5}円 支払い{mark} {'・'.join(order['items'])}")
    total += order["amount"]

print("合計:", total, "円")
ShellScript
python 08_load.py
Plaintext
1001 山田 太郎  1200円 支払い済 ノート・ペン
1002 佐藤 花子   450円 支払い未 ファイル
1003 鈴木 一郎  2380円 支払い済 付箋・ノート・はさみ
合計: 4030 円

true は True に戻っているので、if order["paid"] のようにそのまま条件に使えます。金額の amount も数として読まれるので、int() で変えなくても足し算ができます。

ないかもしれないキーはget()で読む

API の応答では、値が null だったり、キーそのものがなかったりすることがあります。ないかもしれないキーは、data["キー"] ではなく get() で読みます。

Python
import json

with open("data/orders_2026-12-05.json", encoding="utf-8") as f:
    data = json.load(f)

for order in data["orders"]:
    # coupon は null(None)のことがある。note はどの注文にもない
    coupon = order["coupon"] or "なし"
    note = order.get("note", "")
    print(order["id"], "クーポン:", coupon, "メモ:", repr(note))

try:
    print(data["orders"][0]["note"])
except KeyError as e:
    print("KeyError:", e)
ShellScript
python 09_get.py
Plaintext
1001 クーポン: なし メモ: ''
1002 クーポン: WINTER メモ: ''
1003 クーポン: なし メモ: ''
KeyError: 'note'

order.get("note", "") は、note がなければ2つ目の引数の "" を返します。order["note"] と書くと、最後の行のように KeyError で止まります。

null は None になるので、order["coupon"] or "なし" のように、None のときの値を決めておくと扱いやすくなります。

数のキーは文字列に、タプルはリストに変わる

JSON のキーは文字列だけです。そのため、数をキーにした辞書を保存すると、読み直したときにキーが文字列に変わります。

Python
import json

before = {1: "一月", 2: "二月", "point": (10, 20)}
text = json.dumps(before, ensure_ascii=False)
after = json.loads(text)

print("書いた JSON:", text)
print("戻した値  :", after)
print("同じか    :", before == after)
print("数のキーで:", after.get(1), "/ 文字のキーで:", after.get("1"))
ShellScript
python 10_roundtrip.py
Plaintext
書いた JSON: {"1": "一月", "2": "二月", "point": [10, 20]}
戻した値  : {'1': '一月', '2': '二月', 'point': [10, 20]}
同じか    : False
数のキーで: None / 文字のキーで: 一月

キーの 1 は "1" に、タプルの (10, 20) はリストの [10, 20] になりました。そのため、元の辞書と同じかを比べると False です。

読み直したあとに after[1] で取り出そうとすると、値が見つかりません。数のキーで使いたいときは、読んだあとに int() で変えます。

datetime・Decimal・setを保存する:default=で文字列にし、読むときに戻す

datetime・Decimal・set は、そのままでは JSON にできず、TypeError で止まります。json.dump() の default= に変換の関数を渡して文字列やリストにし、読むときに元の型へ戻します。

そのままではTypeError: Object of type datetime is not JSON serializable

集計の結果に、取得した日時(datetime)・税率(Decimal。計算で誤差を出さない小数)・使われたクーポン(set。重なりのない集まり)を入れて保存しようとしました。

Python
import json
from datetime import datetime, timedelta, timezone
from decimal import Decimal

JST = timezone(timedelta(hours=9))

values = {
    "fetched_at": datetime(2026, 12, 5, 9, 30, tzinfo=JST),  # 取得した日時
    "tax_rate": Decimal("0.10"),  # 計算の誤差を出さない小数
    "coupons": {"WINTER"},  # 重なりのない集まり(set)
}

for key, value in values.items():
    try:
        json.dumps({key: value})
    except TypeError as e:
        print(f"{key:10} -> TypeError: {e}")
ShellScript
python 11_typeerror.py
Plaintext
fetched_at -> TypeError: Object of type datetime is not JSON serializable
tax_rate   -> TypeError: Object of type Decimal is not JSON serializable
coupons    -> TypeError: Object of type set is not JSON serializable

3つとも「JSON にできない(not JSON serializable)」という TypeError になりました。JSON で書けるのは、上の表の6種類だけだからです。

default=に変換の関数を渡す

default= に渡した関数は、JSON にできない値が出てきたときだけ呼ばれます。その値を、JSON にできる値にして返します。

Python
import json
from datetime import datetime, timedelta, timezone
from decimal import Decimal

JST = timezone(timedelta(hours=9))


def to_json(obj):
    """JSON にできない値を、JSON にできる値へ変える"""
    if isinstance(obj, datetime):
        return obj.isoformat()  # '2026-12-05T09:30:00+09:00' の形の文字列
    if isinstance(obj, Decimal):
        return str(obj)  # '0.10' のまま残す
    if isinstance(obj, set):
        return sorted(obj)  # 並びをそろえたリスト
    raise TypeError(f"{type(obj).__name__} は JSON にできません")


summary = {
    "fetched_at": datetime(2026, 12, 5, 9, 30, tzinfo=JST),
    "tax_rate": Decimal("0.10"),
    "coupons": {"WINTER", "NEWYEAR"},
    "total": 4030,
}

with open("summary.json", "w", encoding="utf-8") as f:
    json.dump(summary, f, ensure_ascii=False, indent=2, default=to_json)

with open("summary.json", encoding="utf-8") as f:
    print(f.read())

# 変換の関数が None を返すと、エラーにならずに null で保存されてしまう
print(json.dumps({"raw": b"abc"}, default=lambda obj: None))
try:
    json.dumps({"raw": b"abc"}, default=to_json)
except TypeError as e:
    print("TypeError:", e)
ShellScript
python 12_default.py
Plaintext
{
  "fetched_at": "2026-12-05T09:30:00+09:00",
  "tax_rate": "0.10",
  "coupons": [
    "NEWYEAR",
    "WINTER"
  ],
  "total": 4030
}
{"raw": null}
TypeError: bytes は JSON にできません

datetime は isoformat() で "2026-12-05T09:30:00+09:00" の形の文字列に、Decimal は str() で "0.10" に、set は並べ替えたリストになりました。

関数の最後の raise TypeError は消さないでください。出力の最後の2行のとおり、None を返す関数にすると、変換できない値が黙って null で保存されます。知らない型はエラーにして止めます。

読み込んだ文字列をdatetime・Decimal・setに戻す

保存した summary.json を読むと、datetime も Decimal も、ただの文字列として返ります。JSON には型の情報が残らないので、どのキーを何に戻すかは、読む側で決めて書きます。

Python
import json
from datetime import datetime
from decimal import Decimal

with open("summary.json", encoding="utf-8") as f:
    raw = json.load(f)

print("読んだまま:", {k: type(v).__name__ for k, v in raw.items()})

summary = {
    "fetched_at": datetime.fromisoformat(raw["fetched_at"]),
    "tax_rate": Decimal(raw["tax_rate"]),
    "coupons": set(raw["coupons"]),
    "total": raw["total"],
}
print("戻したあと:", {k: type(v).__name__ for k, v in summary.items()})
print("税込み    :", summary["total"] * (1 + summary["tax_rate"]))
print("取得した日:", summary["fetched_at"].strftime("%Y年%m月%d日 %H時%M分"))

# 数として書かれた小数を Decimal で読む
print(json.loads('{"price": 1200.10}'))
print(json.loads('{"price": 1200.10}', parse_float=Decimal))
ShellScript
python 13_restore.py
Plaintext
読んだまま: {'fetched_at': 'str', 'tax_rate': 'str', 'coupons': 'list', 'total': 'int'}
戻したあと: {'fetched_at': 'datetime', 'tax_rate': 'Decimal', 'coupons': 'set', 'total': 'int'}
税込み    : 4433.00
取得した日: 2026年12月05日 09時30分
{'price': 1200.1}
{'price': Decimal('1200.10')}

datetime.fromisoformat() は、isoformat() で書いた文字列を datetime に戻します。

Decimal は Decimal(文字列)、set は set(リスト) で戻せました。戻したあとは、税込みの計算や日付の表示がそのままできます。

小数が数として書かれた JSON なら、json.loads() に parse_float=Decimal を付けると、float を通さずに Decimal で読めます。出力の最後の2行のとおり、ふつうに読むと 1200.1 になり、1200.10 の0が消えます。

JSONDecodeErrorの切り分け:メッセージの行と列から原因を探す

JSONDecodeError は、読もうとした文字が JSON の書き方に合っていないときに出ます。メッセージの最後の line 6 column 3 のような部分が、何行目の何文字目でつまずいたかです。まずその場所と、1つ前の行を見ます。

この記事で起こしたエラーのメッセージと、よくある原因をまとめました。メッセージは Python 3.12 のもので、バージョンによって文が変わることがあります。

メッセージよくある原因確かめた節
Expecting value: line 1 column 1 (char 0)空のファイル・空の応答・HTML のエラー画面空のファイル
Unexpected UTF-8 BOMBOM 付きのファイルを utf-8 で読んだBOM
Expecting value(途中の行)最後の要素の後ろにカンマがある末尾のカンマ
Expecting property name enclosed in double quotes' で囲んでいる(str() で保存した)シングルクォート
Unterminated string・Expecting ',' delimiter途中で切れている途中で切れた
Extra dataJSON が2つ以上並んでいる("a" で追記した)途中で切れた
JSONDecodeError のメッセージと原因

末尾のカンマ:行と列を見て、1つ前の行を確かめる

次の broken.json は、2件目の注文の後ろにカンマが残っています。Python の辞書やリストなら書いてもよいカンマですが、JSON では書けません。

JSON
{
  "date": "2026-12-05",
  "orders": [
    {"id": 1001, "amount": 1200},
    {"id": 1002, "amount": 450},
  ]
}

このファイルを json.load() で読むと、次のように止まります。

Python
import json

with open("broken.json", encoding="utf-8") as f:
    data = json.load(f)
ShellScript
python 14_decode_error.py
Plaintext
Traceback (most recent call last):
  File "~/demo/14_decode_error.py", line 4, in <module>
    data = json.load(f)
           ^^^^^^^^^^^^
  File "~/.local/share/uv/python/cpython-3.12.16-macos-aarch64-none/lib/python3.12/json/__init__.py", line 293, in load
    return loads(fp.read(),
           ^^^^^^^^^^^^^^^^
  File "~/.local/share/uv/python/cpython-3.12.16-macos-aarch64-none/lib/python3.12/json/__init__.py", line 346, in loads
    return _default_decoder.decode(s)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "~/.local/share/uv/python/cpython-3.12.16-macos-aarch64-none/lib/python3.12/json/decoder.py", line 338, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "~/.local/share/uv/python/cpython-3.12.16-macos-aarch64-none/lib/python3.12/json/decoder.py", line 356, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 6 column 3 (char 109)

最後の行の line 6 column 3 は、6行目の ] の位置です。カンマのあとに次の値が来るはずなのに ] が来たので、「値が来るはず(Expecting value)」と言っています。間違いはエラーの位置ではなく、その1つ前の行の最後のカンマです。

JSONDecodeError には、lineno(行)・colno(何文字目)・msg(理由)が入っています。これを使って、つまずいた行を表示する関数を作っておくと、探す手間が減ります。

Python
import json


def load_json(path):
    """JSON を読む。壊れていたら、どの行のどこかを表示して止める"""
    with open(path, encoding="utf-8") as f:
        text = f.read()
    try:
        return json.loads(text)
    except json.JSONDecodeError as e:
        lines = text.splitlines() or [""]
        print(f"{path} の {e.lineno} 行目 {e.colno} 文字目: {e.msg}")
        print(f"{e.lineno:>4} | {lines[e.lineno - 1]}")
        print("     | " + " " * (e.colno - 1) + "^")
        if e.lineno > 1:
            print(f"{e.lineno - 1:>4} | {lines[e.lineno - 2]}  ← 1つ前の行も見る")
        raise


try:
    data = load_json("broken.json")
except json.JSONDecodeError:
    print("読み込みをやめました")
ShellScript
python 15_where.py
Plaintext
broken.json の 6 行目 3 文字目: Expecting value
   6 |   ]
     |   ^
   5 |     {"id": 1002, "amount": 450},  ← 1つ前の行も見る
読み込みをやめました

^ の位置と1つ前の行を並べたので、5行目の最後のカンマが原因だとすぐ分かります。カンマを消せば読めます。

Expecting value: line 1 column 1:空のファイル・JSONでない応答

line 1 column 1 (char 0) は、1文字目から JSON ではなかった、という意味です。中身が空のときと、JSON 以外のものが入っているときに出ます。

Python
import json

cases = {
    "空のファイル": "",
    "空白と改行だけ": "\n  \n",
    "HTML のエラー画面": "<!DOCTYPE html>\n<html><body>503 Service Unavailable</body></html>",
}

for name, text in cases.items():
    try:
        json.loads(text)
    except json.JSONDecodeError as e:
        print(f"{name} -> {e}")
ShellScript
python 16_empty.py
Plaintext
空のファイル -> Expecting value: line 1 column 1 (char 0)
空白と改行だけ -> Expecting value: line 3 column 1 (char 4)
HTML のエラー画面 -> Expecting value: line 1 column 1 (char 0)

空のファイルと、HTML のエラー画面で同じメッセージになりました。API が混んでいたり、URL を間違えたりすると、JSON ではなく HTML のエラー画面が返ってくることがあります。

API の応答で出たときは、json.loads() の前に、ステータスコード(200 など)と、応答の最初の数十文字を表示して確かめてください。ファイルで出たときは、ファイルの大きさが0バイトでないかを見ます。

Unexpected UTF-8 BOM:utf-8-sigで読む

ファイルの先頭に BOM(Byte Order Mark。「このファイルは UTF-8 です」という3バイトの目印)が付いていると、encoding="utf-8" では読めません。Windows のアプリで保存したファイルに付いていることがあります。

Python
import json

# BOM 付きの UTF-8 で保存されたファイルを作る(Windows のメモ帳などで保存すると付くことがある)
with open("bom.json", "w", encoding="utf-8-sig") as f:
    f.write('{"customer": "山田 太郎"}')

with open("bom.json", "rb") as f:
    print("先頭のバイト:", f.read(6))

try:
    with open("bom.json", encoding="utf-8") as f:
        json.load(f)
except json.JSONDecodeError as e:
    print("utf-8     ->", e)

with open("bom.json", encoding="utf-8-sig") as f:
    print("utf-8-sig ->", json.load(f))

with open("bom.json", "rb") as f:
    print("bytes     ->", json.loads(f.read()))
ShellScript
python 17_bom.py
Plaintext
先頭のバイト: b'\xef\xbb\xbf{"c'
utf-8     -> Unexpected UTF-8 BOM (decode using utf-8-sig): line 1 column 1 (char 0)
utf-8-sig -> {'customer': '山田 太郎'}
bytes     -> {'customer': '山田 太郎'}

先頭の \xef\xbb\xbf が BOM です。utf-8 で開くと JSONDecodeError になり、メッセージにも「utf-8-sig で読んで」と出ています。

encoding="utf-8-sig" で開くと、BOM を取り除いて読めました。bytes のまま json.loads() に渡したときも、BOM を見分けて読めています。

Expecting property name enclosed in double quotes:シングルクォート

JSON の文字列とキーは、"(ダブルクォート)で囲む決まりです。'(シングルクォート)で囲むと読めません。よくあるのは、辞書を str() や print() の形のまま保存してしまったときです。

Python
import ast
import json

data = {"id": 1001, "paid": True, "coupon": None}

# まちがい:辞書を str() で文字にして保存した
with open("str_saved.json", "w", encoding="utf-8") as f:
    f.write(str(data))

with open("str_saved.json", encoding="utf-8") as f:
    text = f.read()
print("保存された中身:", text)
try:
    json.loads(text)
except json.JSONDecodeError as e:
    print("JSONDecodeError:", e)

print("json.dumps なら:", json.dumps(data))

# すでに str() で保存してしまったファイルは、ast.literal_eval で Python の値として読める
print("literal_eval  :", ast.literal_eval(text))
ShellScript
python 18_quote.py
Plaintext
保存された中身: {'id': 1001, 'paid': True, 'coupon': None}
JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
json.dumps なら: {"id": 1001, "paid": true, "coupon": null}
literal_eval  : {'id': 1001, 'paid': True, 'coupon': None}

str() で書いた中身は 'id' と ' で囲まれ、True・None も Python の書き方のままです。そのため2文字目の ' でつまずきました。json.dumps() なら、"id"・true・null と JSON の書き方になります。

すでに str() で保存してしまったファイルは、ast.literal_eval()(Python の値の書き方の文字を、安全に値へ戻す関数)で読めます。読めたら、json.dump() で保存し直しておきます。

Unterminated string・Extra data:途中で切れた・JSONが2つ並んだ

書き込みや通信が途中で止まって、JSON が途中で切れていると、どこで切れたかによってメッセージが変わります。反対に、JSON が2つ並んでいると Extra data になります。

Python
import json

full = json.dumps({"orders": [{"id": 1001, "customer": "山田 太郎"}]}, ensure_ascii=False)
print("完全な JSON:", full)

# 途中で切れた JSON(書き込みや通信が途中で止まった)
for cut in (12, 30, 45):
    try:
        json.loads(full[:cut])
    except json.JSONDecodeError as e:
        print(f"{cut:2}文字で切れた -> {e}")

# "a"(追記)で json.dump を2回すると、JSON が2つ並んで読めなくなる
for order_id in (1001, 1002):
    with open("appended.json", "a", encoding="utf-8") as f:
        json.dump({"id": order_id}, f)
with open("appended.json", encoding="utf-8") as f:
    text = f.read()
print("追記したファイル:", text)
try:
    json.loads(text)
except json.JSONDecodeError as e:
    print("JSONDecodeError:", e)
ShellScript
python 19_truncated.py
Plaintext
完全な JSON: {"orders": [{"id": 1001, "customer": "山田 太郎"}]}
12文字で切れた -> Expecting value: line 1 column 13 (char 12)
30文字で切れた -> Unterminated string starting at: line 1 column 26 (char 25)
45文字で切れた -> Expecting ',' delimiter: line 1 column 46 (char 45)
追記したファイル: {"id": 1001}{"id": 1002}
JSONDecodeError: Extra data: line 1 column 13 (char 12)

同じ JSON でも、切れた場所によって Expecting value・Unterminated string(文字列が閉じていない)・Expecting ',' delimiter(カンマが来るはず)と変わりました。

Expecting value と Expecting ',' delimiter の位置(char)は、切れた文字数と同じ、つまりファイルの最後です。

Unterminated string は、閉じていない文字列の始まりの位置を指します。位置がファイルの最後か、その近くなら、途中で切れたと考えます。

Extra data は、1つ目の JSON のあとに、まだ文字が続いているという意味です。"a"(追記)で開いて json.dump() を2回すると、{...}{...} と並んでこうなります。追記したいときは、あとの節の JSON Lines を使います。

書きかけのファイルを残さない保存のしかた

途中で切れたファイルは、保存の途中でエラーが出たり、処理が止められたりしたときにできます。これを防ぐには、同じフォルダの一時ファイルに書き切ってから、os.replace() で本物のファイルと入れ替えます。

Python
import json
import os
import tempfile
from pathlib import Path


def save_json(path, data):
    """一時ファイルに書き切ってから、本物のファイルと入れ替える"""
    path = Path(path)
    fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=path.name, suffix=".tmp")
    try:
        with open(fd, "w", encoding="utf-8") as f:
            json.dump(data, f, ensure_ascii=False, indent=2)
        os.replace(tmp, path)  # 同じフォルダの中なら、入れ替えは一度に終わる
    except BaseException:
        os.remove(tmp)
        raise


good = {"orders": [{"id": 1001}, {"id": 1002}]}
bad = {"orders": [{"id": 1001}, {"id": 1002, "fetched_at": object()}]}  # 2件目で TypeError になる

# ふつうに上書きすると、書きかけのファイルが残る
with open("plain.json", "w", encoding="utf-8") as f:
    json.dump(good, f)
try:
    with open("plain.json", "w", encoding="utf-8") as f:
        json.dump(bad, f)
except TypeError as e:
    print("plain.json  : TypeError で止まった")
print("plain.json の中身:", Path("plain.json").read_text(encoding="utf-8"))

# save_json なら、前のファイルがそのまま残る
save_json("safe.json", good)
try:
    save_json("safe.json", bad)
except TypeError as e:
    print("safe.json   : TypeError で止まった")
print("safe.json の中身 :", json.loads(Path("safe.json").read_text(encoding="utf-8")))
print("残った一時ファイル:", sorted(p.name for p in Path(".").glob("*.tmp")))
ShellScript
python 20_atomic.py
Plaintext
plain.json  : TypeError で止まった
plain.json の中身: {"orders": [{"id": 1001}, {"id": 1002, "fetched_at": 
safe.json   : TypeError で止まった
safe.json の中身 : {'orders': [{'id': 1001}, {'id': 1002}]}
残った一時ファイル: []

ふつうに "w" で上書きした plain.json は、2件目の途中で TypeError になり、"fetched_at": で切れたファイルが残りました。次に読むと JSONDecodeError になるファイルです。

save_json() で書いた safe.json は、エラーが出ても前の中身がそのまま残り、一時ファイルも消えています。"w" で開いた時点で前の中身は消えるので、毎日上書きするファイルほど、この書き方が安心です。

一時ファイルは、tempfile.mkstemp(dir=...) で本物と同じフォルダに作ります。別のドライブなどに作ると、os.replace() が失敗することがあるためです。

Windows で、ほかのアプリがファイルを開いているときに入れ替えられるかは、Windows で未確認です。

大きなデータや追記にはJSON Lines:1行に1件のJSONを書く

毎日の取得結果を足していくときや、件数が多いときは、1行に1件の JSON を書く JSON Lines が向いています。"a" で開いて1行ずつ足せて、読むときも1行ずつ読めます。

1件ずつ追記する

JSON Lines(拡張子は .jsonl が多い)は、ファイル全体を1つの JSON にせず、1行ごとに独立した JSON を書く形式です。1件を json.dumps() で1行の文字列にし、最後に改行を付けて書きます。

Python
import json

import fake_api

data = json.loads(fake_api.get("orders"))

# 1件を1行にして追記する("a" で開く)
with open("orders.jsonl", "a", encoding="utf-8") as f:
    for order in data["orders"]:
        order["date"] = data["date"]
        f.write(json.dumps(order, ensure_ascii=False) + "\n")

# あとから1件だけ足す
with open("orders.jsonl", "a", encoding="utf-8") as f:
    late = {"id": 1004, "customer": "高橋 涼", "items": ["ペン"], "amount": 150,
            "paid": True, "coupon": None, "date": "2026-12-05"}
    f.write(json.dumps(late, ensure_ascii=False) + "\n")

with open("orders.jsonl", encoding="utf-8") as f:
    print(f.read(), end="")
ShellScript
python 21_jsonl_write.py
Plaintext
{"id": 1001, "customer": "山田 太郎", "items": ["ノート", "ペン"], "amount": 1200, "paid": true, "coupon": null, "date": "2026-12-05"}
{"id": 1002, "customer": "佐藤 花子", "items": ["ファイル"], "amount": 450, "paid": false, "coupon": "WINTER", "date": "2026-12-05"}
{"id": 1003, "customer": "鈴木 一郎", "items": ["付箋", "ノート", "はさみ"], "amount": 2380, "paid": true, "coupon": null, "date": "2026-12-05"}
{"id": 1004, "customer": "高橋 涼", "items": ["ペン"], "amount": 150, "paid": true, "coupon": null, "date": "2026-12-05"}

あとから足した1004番も、前の行を読み直さずに最後へ足せました。ふつうの JSON では、1件足すのにファイル全体を読んで書き直す必要があります。

1行に収めるので、indent は付けません。ensure_ascii=False は、日本語をそのまま残すために付けています。

1行ずつ読み、壊れた行だけ飛ばす

読むときは、ファイルを for で1行ずつ回して、行ごとに json.loads() します。ファイル全体を一度にメモリへ読み込まないので、大きなファイルでも読めます。

次の例では、書き込みの途中で止まったように、最後の行を途中で切ってから読みます。

Python
import json

# 書き込みの途中で止まり、最後の行が切れたとする
with open("orders.jsonl", "a", encoding="utf-8") as f:
    f.write('{"id": 1005, "customer": "伊藤')

total = 0
with open("orders.jsonl", encoding="utf-8") as f:
    for lineno, line in enumerate(f, start=1):
        if not line.strip():
            continue  # 空の行は飛ばす
        try:
            order = json.loads(line)
        except json.JSONDecodeError as e:
            print(f"{lineno} 行目を飛ばしました: {e.msg}")
            continue
        total += order["amount"]
        print(lineno, order["id"], order["customer"], order["amount"])

print("合計:", total, "円")
ShellScript
python 22_jsonl_read.py
Plaintext
1 1001 山田 太郎 1200
2 1002 佐藤 花子 450
3 1003 鈴木 一郎 2380
4 1004 高橋 涼 150
5 行目を飛ばしました: Unterminated string starting at
合計: 4180 円

壊れた5行目だけを飛ばして、残りの4件は読めました。ふつうの JSON なら、1か所切れただけでファイル全体が読めなくなります。

飛ばした行があったことは、上のように行の番号と一緒に表示しておきます。黙って飛ばすと、件数が減ったことに気づけません。

JSON・JSON Lines・CSVの使い分け

僕は次のように使い分けています。

保存するもの形式理由
API の応答を丸ごと・設定JSON入れ子のまま保存でき、人が読んで直せる
毎回の取得結果を足していく・件数が多いJSON Lines追記でき、1行ずつ読める。1行壊れても残りは読める
Excel で開く表CSVExcel でそのまま開ける。入れ子のデータは書けない
JSON・JSON Lines・CSV の使い分け

Excel で開く表にしたいときの CSV の書き方と、文字化けしない文字コードの選び方はこちらにまとめています。

サンプルコードで全体像を掴む:取得→保存→読み直しを1つにまとめる

ここまでの書き方をつないで、「その日のファイルがあれば読み、なければ Web API から取得して保存する」スクリプトにしました。保存は書きかけを残さない save_json()、日時は default= で文字列にして、読むときに datetime へ戻します。

orders_report.pyの全体

23_orders_report.py の全体です。cache フォルダに、日付入りの名前で保存します。

Python
"""Web API の注文を取得して JSON に保存し、保存したファイルから集計する"""
import json
import os
import tempfile
from datetime import datetime, timedelta, timezone
from decimal import Decimal
from pathlib import Path

import fake_api

JST = timezone(timedelta(hours=9))
CACHE_DIR = Path(__file__).parent / "cache"
TAX_RATE = Decimal("0.10")


def to_json(obj):
    if isinstance(obj, datetime):
        return obj.isoformat()
    if isinstance(obj, Decimal):
        return str(obj)
    raise TypeError(f"{type(obj).__name__} は JSON にできません")


def save_json(path, data):
    fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=path.name, suffix=".tmp")
    try:
        with open(fd, "w", encoding="utf-8") as f:
            json.dump(data, f, ensure_ascii=False, indent=2, default=to_json)
        os.replace(tmp, path)
    except BaseException:
        os.remove(tmp)
        raise


def load_json(path):
    with open(path, encoding="utf-8") as f:
        try:
            return json.load(f)
        except json.JSONDecodeError as e:
            raise SystemExit(f"{path.name} が壊れています({e.lineno} 行目 {e.colno} 文字目: {e.msg})")


def get_orders(date):
    """その日のファイルがあれば読み、なければ Web API から取って保存する"""
    path = CACHE_DIR / f"orders_{date}.json"
    if path.exists():
        print("保存済みのファイルを読みます:", path.name)
    else:
        print("Web API から取得して保存します:", path.name)
        data = json.loads(fake_api.get("orders"))
        data["fetched_at"] = datetime.now(JST)
        CACHE_DIR.mkdir(exist_ok=True)
        save_json(path, data)
    data = load_json(path)
    data["fetched_at"] = datetime.fromisoformat(data["fetched_at"])  # 文字列から戻す
    return data


def main():
    data = get_orders("2026-12-05")
    paid = [o for o in data["orders"] if o["paid"]]
    total = sum(o["amount"] for o in paid)
    print("取得した日時:", data["fetched_at"].strftime("%Y-%m-%d %H:%M"))
    print(f"支払い済み  : {len(paid)} 件 {total} 円(税込み {total * (1 + TAX_RATE):.0f} 円)")


if __name__ == "__main__":
    main()

load_json() は、ファイルが壊れていたら、ファイル名と行・列を出して止めます。毎日動かすスクリプトなら、どのファイルを直せばよいかがすぐ分かります。

2回動かして、2回目は保存したファイルを読む

1回目は cache フォルダにファイルがないので、Web API(の代わりの fake_api.py)から取得して保存します。

ShellScript
python 23_orders_report.py
Plaintext
Web API から取得して保存します: orders_2026-12-05.json
取得した日時: 2026-12-05 19:41
支払い済み  : 2 件 3580 円(税込み 3938 円)

同じ日にもう一度動かすと、保存済みのファイルを読みます。

ShellScript
python 23_orders_report.py
Plaintext
保存済みのファイルを読みます: orders_2026-12-05.json
取得した日時: 2026-12-05 19:41
支払い済み  : 2 件 3580 円(税込み 3938 円)

2回目は API を呼ばずに、同じ集計になりました。取得した日時も、文字列から datetime に戻して表示できています。API に回数の制限があるときや、あとで同じデータで調べ直したいときに使える形です。

よくある質問

JSON にコメントは書けますか?

書けません。// などのコメントを書くと JSONDecodeError になります(下の出力の1)。

メモを残したいときは、"_comment": "…" のように、使わないキーと値として書いておく方法があります。

キーの順番は保たれますか?並べ替えて保存できますか?

Python の辞書は入れた順番を覚えているので、json.dump() もその順番で書きます。

キーの名前の順に並べたいときは sort_keys=True を付けます(下の出力の2)。

NaN(数でない値)を保存するとどうなりますか?

エラーにならず、NaN と書かれます。これは JSON の決まりにない書き方なので、ほかの言語やツールで読めないことがあります。

allow_nan=False を付けると、保存するときに ValueError で止められます(下の出力の3)。

JSON ファイルを小さくしたいです。

indent を付けず、separators=(",", ":") でカンマとコロンの後ろの空白をなくします。この記事の注文の一覧では、633 バイトが 372 バイトになりました(下の出力の4)。

pathlib の Path で読み書きできますか?

できます。json.loads(path.read_text(encoding="utf-8")) で読み、path.write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8") で書きます(下の出力の5)。

質問の答えで確かめた出力です。

Python
import json
from pathlib import Path

data = {"b": 2, "a": 1, "name": "山田"}

print("1. コメント      :", end=" ")
try:
    json.loads('{\n  "a": 1  // コメント\n}')
except json.JSONDecodeError as e:
    print("JSONDecodeError:", e)

print("2. sort_keys     :", json.dumps(data, ensure_ascii=False, sort_keys=True))

print("3. NaN           :", json.dumps({"rate": float("nan")}))
try:
    json.dumps({"rate": float("nan")}, allow_nan=False)
except ValueError as e:
    print("   allow_nan=False:", "ValueError:", e)

orders = json.loads(Path("api/orders.json").read_bytes())
pretty = json.dumps(orders, ensure_ascii=False, indent=2)
compact = json.dumps(orders, ensure_ascii=False, separators=(",", ":"))
print("4. 大きさ        :", "indent=2", len(pretty.encode()), "バイト / separators", len(compact.encode()), "バイト")

path = Path("faq.json")
path.write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8")
print("5. pathlib       :", json.loads(path.read_text(encoding="utf-8")))
ShellScript
python 24_faq.py
Plaintext
1. コメント      : JSONDecodeError: Expecting ',' delimiter: line 2 column 11 (char 12)
2. sort_keys     : {"a": 1, "b": 2, "name": "山田"}
3. NaN           : {"rate": NaN}
   allow_nan=False: ValueError: Out of range float values are not JSON compliant: nan
4. 大きさ        : indent=2 633 バイト / separators 372 バイト
5. pathlib       : {'b': 2, 'a': 1, 'name': '山田'}

まとめ:encoding=”utf-8″で開き、ensure_ascii=Falseで書き、エラーは行と列を見る

Python で JSON を読み書きするときは、ファイルを encoding="utf-8" で開き、json.dump()・json.load() に渡します。困ったときは次の順に確かめてください。

  • 関数の違い:ファイルは dump・load、文字列は dumps・loads(s は string)
  • 日本語が \u になる:ensure_ascii=False を付ける。読みやすくするなら indent=2
  • datetime・Decimal・set で TypeError:default= で文字列やリストにし、読むときに fromisoformat() などで戻す
  • JSONDecodeError:メッセージの行と列と、1つ前の行を見る。line 1 column 1 は空か JSON でない中身
  • 書きかけを残さない:一時ファイルに書いて os.replace() で入れ替える
  • 追記や大きなデータ:1行に1件の JSON Lines にする
よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

普段は主にPython開発をしています。
最近はAI駆動開発にも関わっています。