Python 速習チュートリアル

Python の JSON

1. Python における JSON

JSON(JavaScript Object Notation)は、データの保存や交換に用いられる標準的なテキスト形式です。Python には、JSON データを扱うための組み込みモジュールとして json が用意されています。

1.1 json モジュールのインポート

json モジュールを使用するには、まずインポートする必要があります。

import json

2. JSON を Python に変換する (Parse JSON)

JSON 文字列がある場合、json.loads() メソッドを使用してそれをパース(解析)し、Python のディクショナリに変換することができます。

2.1 json.loads() の使用例

JSON 文字列を Python オブジェクトに変換するコードです。

import json

# JSON データのサンプル
x =  '{ "name":"John", "age":30, "city":"New York"}'

# JSON をパースして Python ディクショナリに変換
y = json.loads(x)

# 結果は Python ディクショナリになる
print(y["age"])

3. Python を JSON に変換する

Python オブジェクトがある場合、json.dumps() メソッドを使用してそれを JSON 文字列に変換(シリアライズ)することができます。

3.1 json.dumps() の使用例

Python オブジェクトを JSON 文字列に変換するコードです。

import json

# Python オブジェクト(ディクショナリ)のサンプル
x = {
  "name": "John",
  "age": 30,
  "city": "New York"
}

# JSON 文字列に変換
y = json.dumps(x)

# 結果は JSON 文字列になる
print(y)

3.2 様々な Python オブジェクトの変換

Python の以下のデータ型は、JSON オブジェクトに変換可能です。

  • dict
  • list
  • tuple
  • string
  • int
  • float
  • True
  • False
  • None
import json

print(json.dumps({"name": "John", "age": 30}))
print(json.dumps(["apple", "bananas"]))
print(json.dumps(("apple", "bananas")))
print(json.dumps("hello"))
print(json.dumps(42))
print(json.dumps(31.76))
print(json.dumps(True))
print(json.dumps(False))
print(json.dumps(None))

4. 変換ルールとデータ型

Python から JSON へ変換する際、データ型は以下のようにマッピングされます。

PythonJSON
dictObject
listArray
tupleArray
strString
intNumber
floatNumber
Truetrue
Falsefalse
Nonenull

5. 変換結果のフォーマット (Format the Result)

json.dumps() メソッドには、結果を読みやすく整形するためのパラメータが用意されています。

5.1 indent パラメータの使用

indent パラメータを使用して、インデント(字下げ)の数を指定できます。

import json

x = {
  "name": "John",
  "age": 30,
  "married": True,
  "divorced": False,
  "children": ("Ann","Billy"),
  "pets": None,
  "cars": [
    {"model": "BMW 230", "mpg": 27.5},
    {"model": "Ford Edge", "mpg": 24.1}
  ]
}

# インデント 4 を指定して整形
print(json.dumps(x, indent=4))

5.2 separators パラメータの使用

separators パラメータを使用して、デフォルトのセパレータ(区切り文字)を変更することも可能です。デフォルトは (", ", ": ") です。

# カンマの後にスペースを入れず、コロンの前後も調整
print(json.dumps(x, indent=4, separators=(". ", " = ")))

5.3 データのソート (Order the Result)

sort_keys パラメータを使用すると、結果のキーをアルファベット順にソートできます。

# キーをアルファベット順に並べ替えて出力
print(json.dumps(x, indent=4, sort_keys=True))