Open selfboot opened 7 years ago
Demo Json File:
{
"server": "127.0.0.1",
"key": ["1", "中", "文"],
"port": "测试"
}
Load json with following code:
with open(config_path, 'rb') as f:
try:
"""
# 1
{u'port': '\xe6\xb5\x8b\xe8\xaf\x95', u'key': ['1', '\xe4\xb8\xad', '\xe6\x96\x87'], u'server': '127.0.0.1'}
['1', '\xe4\xb8\xad', '\xe6\x96\x87']
文
"""
config = json.loads(f.read().decode('utf8'), object_hook=_decode_dict)
"""
# 2
{u'port': u'\u6d4b\u8bd5', u'key': [u'1', u'\u4e2d', u'\u6587'], u'server': u'127.0.0.1'}
[u'1', u'\u4e2d', u'\u6587']
文
"""
# config = json.loads(f.read().decode('utf8'))
except ValueError as e:
sys.exit(1)
print(config)
print(config["key"])
print(config["key"][2])
Read the config from json:
As follows:
<type 'str'>
in py2 ) to a unicode string is known as decoding. More: Unicode HOWTOjson.loads
deserialize s (a str or unicode instance containing a JSON document) to a Python object using this conversion table. If s is a str instance and is encoded with an ASCII based encoding other than UTF-8 (e.g. latin-1), then an appropriate encoding name must be specified. Encodings that are not ASCII based (such as UCS-2) are not allowed and should be decoded to unicode first.object_hook
is an optional function that will be called with the result of any object literal decoded (a dict). The return value of object_hook will be used instead of the dict. This feature can be used to implement custom decoders.This conversion table