Python を使用した JSON の読み取り、書き込み、解析
JSON は、人間が簡単に読み書きでき、マシンが簡単に解析して生成できるデータ交換用の軽量データ形式です。これは完全に言語に依存しないテキスト形式です。 JSON データを操作するために、Python には JSON と呼ばれる組み込みパッケージがあります。
JSON文字列の例
s = '{'id':01, 'name': 'Emily', 'language': ['C++', 'Python']}' の構文 JSON の構文のサブセットとみなされます JavaScript 以下を含みます:
- 名前と値のペア: データを表します。名前の後にコロン( : )、名前と値のペアはカンマ( 、 )。
- 中括弧: オブジェクトを保持します。
- 角括弧: 値をカンマで区切った配列を保持します ( 、 )。
キー/名前は二重引用符で囲まれた文字列である必要があり、値は次のデータ型である必要があります。
JSON ファイルの例:
{ 'employee': [ { 'id': '01', 'name': 'Amit', 'department': 'Sales' }, { 'id': '04', 'name': 'sunil', 'department': 'HR' } ] } Python による JSON 文字列の解析
以下のコードでは、JSON を Python オブジェクトに変換します。 JSON 文字列 Python を解析するには、まず JSON モジュールをインポートします。 JSON文字列を変数に保存しました '従業員' そして、この JSON 文字列を Python オブジェクトに変換します。 json.loads() PythonのJSONモジュールのメソッドです。その後、キー「name」を使用して従業員の名前を出力します。 。
Python3
# Python program to convert JSON to Python> import> json> # JSON string> employee> => '{'id':'09', 'name': 'Nitin', 'department':'Finance'}'> # Convert string to Python dict> employee_dict> => json.loads(employee)> print> (employee_dict)> print> (employee_dict[> 'name'> ])> |
出力
{'id': '09', 'name': 'Nitin', 'department': 'Finance'} Nitin PythonはJSONファイルを読み込みます
次のような JSON ファイルがあるとします。
ここでは、open() 関数を使用して JSON ファイルを読み取りました。次に、json.load() メソッドを使用してファイルが解析され、data という名前の辞書が得られます。
Python3
import> json> # Opening JSON file> f> => open> (> 'data.json'> ,)> # returns JSON object as> # a dictionary> data> => json.load(f)> # Iterating through the json> # list> for> i> in> data[> 'emp_details'> ]:> > print> (i)> # Closing file> f.close()> |
出力:
Python 辞書を JSON に変換する
以下のコードでは、 Python辞書 を使用して JSON オブジェクトに変換します json.dumps() PythonのJSONモジュールのメソッドです。まず JSON モジュールをインポートし、次にいくつかのキーと値のペアで小さな辞書を作成し、それを「indent=4」で json.dumps() メソッドに渡して、この Python 辞書を JSON オブジェクトに変換します。 indent の値を 4 に指定したため、出力に見られるように、各データの前に 4 つの空白があります。
Python3
# Python program to convert> # Python to JSON> import> json> > # Data to be written> dictionary> => {> > 'id'> :> '04'> ,> > 'name'> :> 'sunil'> ,> > 'department'> :> 'HR'> }> > # Serializing json> json_object> => json.dumps(dictionary, indent> => 4> )> print> (json_object)> |
出力
{ 'id': '04', 'name': 'sunil', 'department': 'HR' } 次のタイプの Python オブジェクトを JSON 文字列に変換できます。
Python オブジェクトとそれに相当する JSON への変換:
| パイソン | JSON に相当するもの |
|---|---|
| 辞書 | 物体 |
| リスト、タプル | 配列 |
| str | 弦 |
| 整数、浮動小数点 | 番号 |
| 真実 | 真実 |
| 間違い | 間違い |
| なし | ヌル |
Python で JSON をファイルに書き込む
JSON モジュールの json.dump() 関数と Python でのファイル処理を使用して、JSON をファイルに書き込むことができます。以下のプログラムでは、sample.json という名前のファイルを書き込みモードで開きます。 'で' 。ファイルが存在しない場合は作成されます。 Json.dump() は Python 辞書を JSON 文字列に変換し、sample.json ファイルに保存します。
Python3
# Python program to write JSON> # to a file> import> json> > # Data to be written> dictionary> => {> > 'name'> :> 'sathiyajith'> ,> > 'rollno'> :> 56> ,> > 'cgpa'> :> 8.6> ,> > 'phonenumber'> :> '9976770500'> }> > with> open> (> 'sample.json'> ,> 'w'> ) as outfile:> > json.dump(dictionary, outfile)> |
出力:
Python のきれいな印刷 JSON
文字列を JSON に変換すると、データは読みにくい形式になります。読みやすくするために、次のような追加の引数を json.dumps() 関数に渡すことで、きれいな印刷を使用できます。 インデント そして ソートキー 以下のコードで使用されているように。
Python3
# Python program to convert JSON to Python> import> json> # JSON string> employee> => '{'id':'09', 'name': 'Nitin', 'department':'Finance'}'> # Convert string to Python dict> employee_dict> => json.loads(employee)> # Pretty Printing JSON string back> print> (json.dumps(employee_dict, indent> => 4> , sort_keys> => True> ))> |
出力
{ 'department': 'Finance', 'id': '09', 'name': 'Nitin' }