json ファイルの構成
Python の辞書型と同様、キーと値を指定します。
{"key_01" : value, "key_02" : value}
{ "key_01" : value, "key_02" : value, "key_03" : value }
辞書型のインデント変換
辞書型を文字列に変換したものに対して辞書型のインデントを行いたい
print(json.dumps(dict_value, indent=4, ensure_ascii=False))
データ型
文字列 | {"name" : "yamada"} | "value" ダブルクオーテーションで囲む。 |
数値 | {"pi" : 3.14} | 0から9の数字、符号、小数点、指数記号が使える。 Integer と Float などの区別はない。 |
ブール | {"status" : True} | true / false |
空欄 | {"content" : null} | null |
オブジェクト | {} 波カッコでネスト | |
リスト | [] カッコでリスト |
ネスト
{ "key_A" :{ "key_01": value, "key_02": value, "key_03": value }, "key_B" :{ "key_01": value, "key_02": value, "key_03": value } }
json ファイルの書き出し
import json sample_dict = { 'key_D': { 'key_01':'pen', 'key_02':'eraser', 'key_03':'ruler' }, 'key_B': { 'fluit':[ 'apple', 'orange', 'grape' ], 'drink':[ 'sprite', 'cola', 'cocoa' ] }, 'key_A': 'carrot', 'key_C': [ 'sprite', 'cola', 'cocoa' ], 'key_E': 'あいうえお' } with open('./sample.json', 'w') as f: json.dump(sample_dict, f)
{"key_D": {"key_01": "pen", "key_02": "eraser", "key_03": "ruler"}, "key_B": {"fluit": ["apple", "orange", "grape"], "drink": ["sprite", "cola", "cocoa"]}, "key_A": "carrot", "key_C": ["sprite", "cola", "cocoa"], "key_E": "\u3042\u3044\u3046\u3048\u304a"}
インデントと文字コードの指定
import json with open('./sample.json', 'w', encoding="utf-8") as f: json.dump(sample_dict, f, indent=4, ensure_ascii=False)
{ "key_D": { "key_01": "pen", "key_02": "eraser", "key_03": "ruler" }, "key_B": { "fluit": [ "apple", "orange", "grape" ], "drink": [ "sprite", "cola", "cocoa" ] }, "key_A": "carrot", "key_C": [ "sprite", "cola", "cocoa" ], "key_E": "あいうえお" }
json ファイルの読み込み
import json with open('sample.json', 'r', encoding="utf-8") as f: json_text = json.load(f) print(json_text)
キーから値を取得
import json with open('sample.json', 'r', encoding="utf-8") as f: json_text = json.load(f) print(json_text['key_A']) #-> carrot print(json_text['key_D']['key_01']) #-> pen
すべてのキーと値を for 文で回す
for key, value in json_text.items(): print() print('key : ', key) print('value : ', value)
key : key_D value : {'key_01': 'pen', 'key_02': 'eraser', 'key_03': 'ruler'} key : key_B value : {'fluit': ['apple', 'orange', 'grape'], 'drink': ['sprite', 'cola', 'cocoa']} key : key_A value : carrot key : key_C value : ['sprite', 'cola', 'cocoa'] key : key_E value : あいうえお
ネストされている場合
for key, value in json_text['key_D'].items(): print() print('key : ', key) print('value : ', value)
json ファイルの更新
import json # json ファイルの読み込み with open('sample.json', 'r', encoding="utf-8") as f: json_text = json.load(f) # 辞書の更新 json_text['key_Z'] = 'add_value' # json ファイルの上書き with open('./sample.json', 'w', encoding="utf-8") as f: json.dump(json_text, f, indent=4, ensure_ascii=False)
dict の操作
すべてのキーの取得
# すべてのキーの取得 key_list = dict.keys()
key の個数の取得
普通に len でとれる
print( len({ 'a': 'test', 'b': 'test' }) )
2
リスト内の辞書の重複を削除する
import json import hashlib dict_list = [ {'test': 'hoge'}, {'test': 'hoge'} ] # ハッシュ値を格納するset hashes = set() # 重複を除外したリストを格納するリスト result = [] for d in dict_list: # 辞書型をシリアライズしてハッシュ値を取得する d_hash = hashlib.sha256(json.dumps(d, sort_keys=True).encode()).hexdigest() if d_hash not in hashes: # ハッシュ値が重複していなければ、リストに要素を追加して、ハッシュ値をセットに格納する result.append(d) hashes.add(d_hash) print(result)