「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 形式の fp (.write() がサポートされている file-like object) へのストリームとして直列化します。
使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import json
#ディクショナリの定義
cft = {"username":"山田",
"city":"東京",
"addr":"品川",
"age":"23"
}
res = json.dumps(cft)
print (res)
#nsure_ascii=Falseを指定
resB = json.dumps(cft,ensure_ascii=False)
print (resB)
#indentを指定
resC = json.dumps(cft,ensure_ascii=False, indent=5)
print (resC)
import json #ディクショナリの定義 cft = {"username":"山田", "city":"東京", "addr":"品川", "age":"23" } res = json.dumps(cft) print (res) #nsure_ascii=Falseを指定 resB = json.dumps(cft,ensure_ascii=False) print (resB) #indentを指定 resC = json.dumps(cft,ensure_ascii=False, indent=5) print (resC)
import json

#ディクショナリの定義
cft = {"username":"山田",
      "city":"東京",
      "addr":"品川",
    "age":"23"
    }

res = json.dumps(cft)
print (res) 

#nsure_ascii=Falseを指定
resB = json.dumps(cft,ensure_ascii=False)
print (resB) 

#indentを指定
resC = json.dumps(cft,ensure_ascii=False, indent=5)
print (resC)

結果

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
{"username": "\u5c71\u7530", "city": "\u6771\u4eac", "addr": "\u54c1\u5ddd", "age": "23"}
{"username": "山田", "city": "東京", "addr": "品川", "age": "23"}
{
"username": "山田",
"city": "東京",
"addr": "品川",
"age": "23"
}
{"username": "\u5c71\u7530", "city": "\u6771\u4eac", "addr": "\u54c1\u5ddd", "age": "23"} {"username": "山田", "city": "東京", "addr": "品川", "age": "23"} { "username": "山田", "city": "東京", "addr": "品川", "age": "23" }
{"username": "\u5c71\u7530", "city": "\u6771\u4eac", "addr": "\u54c1\u5ddd", "age": "23"}
{"username": "山田", "city": "東京", "addr": "品川", "age": "23"}
{
     "username": "山田",
     "city": "東京",
     "addr": "品川",
     "age": "23"
}

 

Python

Posted by arkgame