「Python」ディクショナリをJSONにエンコードする方法
説明
json.dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)
この 変換表 を使って、obj を JSON 形式の str オブジェクトに直列化します。引数は dump() と同じ意味です。
サンプルコード
# coding: utf-8 #!/usr/bin/python3 import json jsonA = {"username":"user001", "age":"23", "addr":"chang fatun", "female":"woman"} md = json.dumps(jsonA) print ("result1: ",md) md2 = json.dumps(jsonA,ensure_ascii=False) print ("result2: ",md2) md3 = json.dumps(jsonA,ensure_ascii=False, indent=4) print ("result3: ",md3)
実行結果
>python test.py
result1: {"username": "user001", "age": "23", "addr": "chang fatun", "female": "woman"} result2: {"username": "user001", "age": "23", "addr": "chang fatun", "female": "woman"} result3: { "username": "user001", "age": "23", "addr": "chang fatun", "female": "woman" }