python json formatting
Generally speaking, an object is formatted in json and then printed or saved to a file as follows:
#coding=utf8
import json
obj = {
"name": "张三",
"phone": "15066668888",
"adress": "天津"
}
print(json.dumps(obj))
# {"name": "\u5f20\u4e09", "phone": "15066668888", "adress": "\u5929\u6d25"}
Chinese formatting
The Chinese inside is unicode encoded by default, which doesn't look good. Then update the dump method:
print(json.dumps(obj))
# {"name": "张三", "phone": "15066668888", "adress": "天津"}
Format words
Without locking, it is still difficult to see the hierarchical relationship of fields when the amount of data is large, and you need to find various formatting tools to see the effect. Then update the dump method:
print(json.dumps(obj, ensure_ascii=False, indent=2))
# {
# "name": "张三",
# "phone": "15066668888",
# "adress": "天津"
# }
Field sorting
I feel that the field sorting is messy, but I still want to sort it by alphabetical series. Then update the dump method:
print(json.dumps(obj, ensure_ascii=False, indent=2))
# {
# "adress": "天津",
# "name": "张三",
# "phone": "15066668888"
# }