Python JSON:JSON ファイルのエンコード (ダンプ)、デコード (ロード)、読み取り
Python の JSON とは?
JSON in Python は、ネットワークを介したテキスト形式としてのデータ交換およびデータ転送のための JavaScript に触発された標準形式です。通常、JSON は文字列またはテキスト形式です。 API とデータベースで使用でき、オブジェクトを名前と値のペアとして表します。 JSON は JavaScript Object Notation の略です。
Python JSON 構文:
JSON はキーと値のペアとして記述されます。
{
"Key": "Value",
"Key": "Value",
}
JSON は と非常によく似ています パイソン辞書。 Python は JSON をサポートしており、JSON として組み込みのライブラリがあります。
Python の JSON ライブラリ
「元帥 ' および 'ピクルス' Python の外部モジュールは JSON のバージョンを維持します Python ライブラリ。 Python で JSON を操作して、エンコードやデコードなどの JSON 関連の操作を実行するには、最初に インポート する必要があります JSON ライブラリとそのための .py ファイル、
import json
以下のメソッドは、JSON Python モジュールで利用できます
| メソッド | 説明 |
|---|---|
| ダンプ() | JSON オブジェクトへのエンコード |
| ダンプ() | ファイルへのエンコードされた文字列の書き込み |
| loads() | JSON 文字列をデコードする |
| load() | JSON ファイルの読み取り中にデコード |
Python から JSON (エンコーディング)
Python の JSON ライブラリは、デフォルトで次の Python オブジェクトの JSON オブジェクトへの変換を実行します
| Python | JSON |
|---|---|
| 口述 | オブジェクト |
| リスト | 配列 |
| ユニコード | 文字列 |
| 数値 – int、long | 数値 - 整数 |
| フロート | 数 – 実数 |
| はい | はい |
| 偽 | 間違っている |
| なし | ヌル |
Python データを JSON に変換することは、エンコード操作と呼ばれます。エンコードは、JSON ライブラリ メソッドの助けを借りて行われます – dumps()
Python での JSON dump()
json.dumps() in Python は、Python の辞書オブジェクトを JSON 文字列データ形式に変換するメソッドです。解析、印刷などの操作のためにオブジェクトを文字列形式にする必要がある場合に便利です。
それでは、Python で最初の json.dumps エンコーディングの例を実行してみましょう:
import json
x = {
"name": "Ken",
"age": 45,
"married": True,
"children": ("Alice","Bob"),
"pets": ['Dog'],
"cars": [
{"model": "Audi A1", "mpg": 15.1},
{"model": "Zeep Compass", "mpg": 18.1}
]
}
# sorting result in asscending order by keys:
sorted_string = json.dumps(x, indent=4, sort_keys=True)
print(sorted_string)
出力:
{"person": {"name": "Kenn", "sex": "male", "age": 28}})
同じ関数 dump() を使用して辞書の JSON ファイルを作成するために、Python が JSON をファイルに書き込む例を見てみましょう。
# here we create new data_file.json file with write mode using file i/o operation
with open('json_file.json', "w") as file_write:
# write json data into file
json.dump(person_data, file_write)
出力:
表示するものはありません...システムで json_file.json が作成されます。以下の JSON をファイルに書き込む Python の例に示すように、そのファイルを確認できます。
JSON から Python へ (デコード)
JSON 文字列のデコードは、組み込みメソッド json.loads() を使用して行われます &json.load() Python の JSON ライブラリの。ここでの変換表は、JSON 文字列の Python でのデコードを実行するのに役立つ JSON オブジェクトから Python オブジェクトへの例を示しています。
| JSON | パイソン |
|---|---|
| オブジェクト | 口述 |
| 配列 | リスト |
| 文字列 | ユニコード |
| 数値 – 整数 | 数値 – int、long |
| 数 – 実数 | フロート |
| はい | はい |
| 偽 | 間違っている |
| ヌル | なし |
json.loads を使用してデコードする基本的な JSON Python の例を見てみましょう。 関数、
import json # json library imported
# json data string
person_data = '{ "person": { "name": "Kenn", "sex": "male", "age": 28}}'
# Decoding or converting JSON format in dictionary using loads()
dict_obj = json.loads(person_data)
print(dict_obj)
# check type of dict_obj
print("Type of dict_obj", type(dict_obj))
# get human object details
print("Person......", dict_obj.get('person'))
出力:
{'person': {'name': 'Kenn', 'sex': 'male', 'age': 28}}
Type of dict_obj <class 'dict'>
Person...... {'name': 'John', 'sex': 'male'}
JSON ファイルのデコードまたは Python での JSON ファイルの解析
ここで、Python parse JSON の例を使用して、Python で JSON ファイルを読み取る方法を学習します。
注: JSON ファイルのデコードは、ファイルの入出力 (I/O) 関連の操作です。 JSON ファイルは、システム上のプログラムで指定した場所に存在する必要があります。
Python 読み取り JSON ファイルの例:
import json
#File I/O Open function for read data from JSON File
with open('X:/json_file.json') as file_object:
# store file data in object
data = json.load(file_object)
print(data)
ヒアデータ 上記の読み込み JSON ファイルの Python の例に示すように、Python のディクショナリ オブジェクトです。
出力:
{'person': {'name': 'Kenn', 'sex': 'male', 'age': 28}}
Python でのコンパクト エンコーディング
JSON ファイルのサイズを小さくする必要がある場合は、Python でコンパクト エンコーディングを使用できます。
例
import json
# Create a List that contains dictionary
lst = ['a', 'b', 'c',{'4': 5, '6': 7}]
# separator used for compact representation of JSON.
# Use of ',' to identify list items
# Use of ':' to identify key and value in dictionary
compact_obj = json.dumps(lst, separators=(',', ':'))
print(compact_obj)
出力:
'["a", "b", "c", {"4": 5, "6": 7}]'
** Here output of JSON is represented in a single line which is the most compact representation by removing the space character from compact_obj ** JSON コードのフォーマット (Pretty print)
- 目的は、人間が理解できる適切な形式のコードを書くことです。プリティ プリンティングの助けを借りて、誰でも簡単にコードを理解できます。
例:
import json
dic = { 'a': 4, 'b': 5 }
''' To format the code use of indent and 4 shows number of space and use of separator is not necessary but standard way to write code of particular function. '''
formatted_obj = json.dumps(dic, indent=4, separators=(',', ': '))
print(formatted_obj)
出力:
{
"a" : 4,
"b" : 5
}
これをよりよく理解するには、インデントを 40 に変更し、出力を観察してください-
JSON コードの注文:
sort_keys Python dumps 関数の引数の属性は、JSON のキーを昇順で並べ替えます。 sort_keys 引数はブール属性です。 true の場合は並べ替えが許可され、それ以外の場合は許可されません。 Python 文字列から JSON への並べ替えの例で理解しましょう。
例
import json
x = {
"name": "Ken",
"age": 45,
"married": True,
"children": ("Alice", "Bob"),
"pets": [ 'Dog' ],
"cars": [
{"model": "Audi A1", "mpg": 15.1},
{"model": "Zeep Compass", "mpg": 18.1}
],
}
# sorting result in asscending order by keys:
sorted_string = json.dumps(x, indent=4, sort_keys=True)
print(sorted_string)
出力:
{
"age": 45,
"cars": [ {
"model": "Audi A1",
"mpg": 15.1
},
{
"model": "Zeep Compass",
"mpg": 18.1
}
],
"children": [ "Alice",
"Bob"
],
"married": true,
"name": "Ken",
"pets": [
"Dog"
]
}
ご覧のとおり、キーの年齢、車、子供などは昇順で並べられています。
Python の複合オブジェクト エンコーディング
複合オブジェクトには 2 つの異なる部分があります
<オール>
例:3 +2i
複雑なオブジェクトのエンコードを実行する前に、変数が複雑かどうかを確認する必要があります。インスタンス メソッドを使用して、変数に格納された値をチェックする関数を作成する必要があります。
オブジェクトが複雑であるか、エンコードに適しているかをチェックするための特定の関数を作成しましょう。
import json
# create function to check instance is complex or not
def complex_encode(object):
# check using isinstance method
if isinstance(object, complex):
return [object.real, object.imag]
# raised error using exception handling if object is not complex
raise TypeError(repr(object) + " is not JSON serialized")
# perform json encoding by passing parameter
complex_obj = json.dumps(4 + 5j, default=complex_encode)
print(complex_obj)
出力:
'[4.0, 5.0]'
Python での複雑な JSON オブジェクトのデコード
JSON で複合オブジェクトをデコードするには、JSON 文字列に複合オブジェクトが含まれているかどうかをチェックする object_hook パラメーターを使用します。 JSON Python の例に文字列で理解しましょう
import json
# function check JSON string contains complex object
def is_complex(objct):
if '__complex__' in objct:
return complex(objct['real'], objct['img'])
return objct
# use of json loads method with object_hook for check object complex or not
complex_object =json.loads('{"__complex__": true, "real": 4, "img": 5}', object_hook = is_complex)
#here we not passed complex object so it's convert into dictionary
simple_object =json.loads('{"real": 6, "img": 7}', object_hook = is_complex)
print("Complex_object......",complex_object)
print("Without_complex_object......",simple_object)
出力:
Complex_object...... (4+5j)
Without_complex_object...... {'real': 6, 'img': 7}
JSON シリアル化クラス JSONEncoder の概要
JSONEncoder クラスは、エンコーディングの実行中に任意の Python オブジェクトをシリアル化するために使用されます。
- デフォルト(o) – サブクラスに実装され、o のシリアル化オブジェクトを返します オブジェクト。
- エンコード(o) – JSON ダンプと同じ Python メソッドは、Python データ構造の JSON 文字列を返します。
- iterencode(o) – 文字列を 1 つずつ表現し、オブジェクト o をエンコードします。
JSONEncoder クラスの encode() メソッドの助けを借りて、以下の Python JSON エンコーダーの例に示すように、任意の Python オブジェクトをエンコードすることもできます。
# import JSONEncoder class from json
from json.encoder import JSONEncoder
colour_dict = { "colour": ["red", "yellow", "green" ]}
# directly called encode method of JSON
JSONEncoder().encode(colour_dict)
出力:
'{"colour": ["red", "yellow", "green"]}' JSON デシリアライゼーション クラス JSONDecoder の概要
JSONDecoder クラスは、デコードの実行中に任意の Python オブジェクトの逆シリアル化に使用されます。
- デフォルト(o) – サブクラスに実装され、デシリアライズされたオブジェクト o を返します オブジェクト。
- デコード(o) – json.loads() メソッドと同じように、JSON 文字列またはデータの Python データ構造を返します。
- raw_decode(o) – Python 辞書を 1 つずつ表現し、オブジェクト o をデコードします。
JSONDecoder クラスの decode() メソッドの助けを借りて、以下の Python JSON デコーダーの例に示すように、JSON 文字列をデコードすることもできます。
import json
# import JSONDecoder class from json
from json.decoder import JSONDecoder
colour_string = '{ "colour": ["red", "yellow"]}'
# directly called decode method of JSON
JSONDecoder().decode(colour_string)
出力:
{'colour': ['red', 'yellow']} URL からの JSON データのデコード:実際の例
指定したURL(https://feeds.citibikenyc.com/stations/stations.json)からCityBike NYC(自転車共有システム)のデータを取得し、辞書形式に変換します。
Python がファイルから JSON を読み込む 例:
注:- requests ライブラリが既に Python にインストールされていることを確認してください。インストールされていない場合は、ターミナルまたは CMD を開いて入力してください
- (Python 3 以降の場合) pip3 インストール リクエスト
import json
import requests
# get JSON string data from CityBike NYC using web requests library
json_response= requests.get("https://feeds.citibikenyc.com/stations/stations.json")
# check type of json_response object
print(type(json_response.text))
# load data in loads() function of json library
bike_dict = json.loads(json_response.text)
#check type of news_dict
print(type(bike_dict))
# now get stationBeanList key data from dict
print(bike_dict['stationBeanList'][0])
出力:
<class 'str'>
<class 'dict'>
{
'id': 487,
'stationName': 'E 20 St & FDR Drive',
'availableDocks': 24,
'totalDocks': 34,
'latitude': 40.73314259,
'longitude': -73.97573881,
'statusValue': 'In Service',
'statusKey': 1,
'availableBikes': 9,
'stAddress1': 'E 20 St & FDR Drive',
'stAddress2': '',
'city': '',
'postalCode': '',
'location': '',
'altitude': '',
'testStation': False,
'lastCommunicationTime': '2018-12-11 10:59:09 PM', 'landMark': ''
}
Python の JSON ライブラリに関連する例外:
- クラス json.JSONDecoderError デコード操作に関連する例外を処理します。 ValueError のサブクラスです。
- 例外 – json.JSONDecoderError(msg, doc)
- 例外のパラメータは、
- msg – フォーマットされていないエラー メッセージ
- doc – 解析された JSON ドキュメント
- pos – 失敗したドキュメントのインデックスを開始
- lineno – 行番号は pos に対応します
- コロン – 桁に対応する列の番号
Python がファイルから JSON を読み込む 例:
import json
#File I/O Open function for read data from JSON File
data = {} #Define Empty Dictionary Object
try:
with open('json_file_name.json') as file_object:
data = json.load(file_object)
except ValueError:
print("Bad JSON file format, Change JSON File")
Python の無限数と NaN 数
JSON Data Interchange Format (RFC – Request For Comments) では Infinite または Nan 値が許可されていませんが、Python-JSON ライブラリには、Infinite および Nan 値に関連する操作を実行するための制限はありません。 JSON が INFINITE および Nan データ型を取得すると、リテラルに変換されます。
例
import json
# pass float Infinite value
infinite_json = json.dumps(float('inf'))
# check infinite json type
print(infinite_json)
print(type(infinite_json))
json_nan = json.dumps(float('nan'))
print(json_nan)
# pass json_string as Infinity
infinite = json.loads('Infinity')
print(infinite)
# check type of Infinity
print(type(infinite))
出力:
Infinity <class 'str'> NaN inf <class 'float'>
JSON 文字列のキーの繰り返し
RFC では、キー名は JSON オブジェクト内で一意である必要があると規定していますが、必須ではありません。 Python JSON ライブラリは、JSON で繰り返されるオブジェクトの例外を発生させません。繰り返されるすべてのキーと値のペアを無視し、最後のキーと値のペアのみを考慮します。
- 例
import json
repeat_pair = '{"a": 1, "a": 2, "a": 3}'
json.loads(repeat_pair)
出力:
{'a': 3} Python での JSON を使用した CLI (コマンド ライン インターフェース)
json.tool JSON プリティプリント構文を検証するためのコマンド ライン インターフェイスを提供します。 CLI の例を見てみましょう
$ echo '{"name" : "Kings Authur" }' | python3 -m json.tool 出力:
{
"name": " Kings Authur "
}
Python での JSON の利点
- コンテナと値の間を簡単に移動できます (JSON から Python、Python から JSON)
- 人が読める (Pretty-print) JSON オブジェクト
- データ処理で広く使用されています。
- 単一のファイルに同じデータ構造がありません。
Python での JSON の実装の制限
- JSON 範囲のデシリアライザーと数値の予測
- JSON 文字列と JSON の配列の最大長、およびオブジェクトのネスト レベル。
Python JSON チート シート
| Python JSON 関数 | 説明 |
|---|---|
| json.dumps(person_data) | JSON オブジェクトの作成 |
| json.dump(person_data, file_write) | Python のファイル I/O を使用して JSON ファイルを作成 |
| compact_obj =json.dumps(データ、セパレーター =(',',':')) | 区切り文字を使用して JSON オブジェクトからスペース文字を削除して JSON オブジェクトをコンパクト化 |
| formatted_obj =json.dumps(dic, indent=4, separators=(‘,’, ‘:‘)) | インデントを使用した JSON コードのフォーマット |
| sorted_string =json.dumps(x, indent=4, sort_keys=True) | JSON オブジェクト キーをアルファベット順に並べ替える |
| complex_obj =json.dumps(4 + 5j、デフォルト=complex_encode) | JSON での Python 複合オブジェクト エンコーディング |
| JSONEncoder().encode(colour_dict) | シリアル化のための JSONEncoder クラスの使用 |
| json.loads(data_string) | json.loads() 関数を使用して Python 辞書の JSON 文字列をデコードする |
| json.loads(‘{“__complex__”:true, “real”:4, “img”:5}’, object_hook =is_complex) | 複雑な JSON オブジェクトの Python へのデコード |
| JSONDecoder().decode(colour_string) | 逆シリアル化による JSON から Python へのデコードの使用 |
Python