Python と JSON

JSON はデータを格納するための構文です.

JSON は JavaScript.

JSON を Python にインポートする

Python は json、JSON.

import json

JSON を Python に変換する (JSON を解析する)

メソッド json.loads() Python.

の結果はPython辞書に格納されます.

import json

x = '{ "name":"patrik", "age":25, "city":"Paris"}'

# パーサー x:
y = json.loads(x)

print(y["city"])

Python オブジェクトを JSON に変換

method を使用して Python オブジェクトを変換できます json.dumps().

import json

# object
x = {"name": "patrik", "age": 25, "city": "Paris"}

# JSON に変換:
y = json.dumps(x)

# 結果は JSON
print(y)

Python オブジェクトは、さまざまなタイプの JSON に変換できます:

  • dict ->オブジェクト
  • tuple ->アレイ
  • string ->文字列
  • list ->配列
  • int ->数値
  • float ->数値
  • True ->true
  • False ->false
  • なし ->null

JSONの美化)

JSON形式を美しくするために、json.dumps() には、結果を読みやすくするためのパラメーターがあります:

import json

x = {
"name": "Adam",
"age": 32.
"single": False,
"children": ("Leo","Arthur"),
"car": [
{"model": "Renault", "year": 2022},
]
}

print(json.dumps(x, indent=4))

Result:

{
"名前": "Adam",
"age": 32,
"single": false,
"children": [
"L\u00e9o",
"Arthur"
],
"車": [
{
"model": "Renault",
"年": 2022
}
]
}

Sort result

パラメータsort_keys:

json.dumps(x, indent=4, sort_keys=True)