selfboot / AnnotatedShadowSocks

Annotated shadowsocks(python version)
Other
3 stars 1 forks source link

Read config from a json file #3

Open selfboot opened 7 years ago

selfboot commented 7 years ago

Read the config from json:

with open(config_path, 'rb') as f:
    try:
        config = json.loads(f.read().decode('utf8'), object_hook=_decode_dict)
    except ValueError as e:
        logging.error('found an error in config.json: %s', e.message)
        sys.exit(1)

As follows:

This conversion table

JSON Python
object dict
array list
string unicode
number (int) int, long
number (real) float
true True
false False
null None
selfboot commented 6 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])