简体   繁体   English

在python中输入“string”到“dict”

[英]type "string" to “dict” in python

I am a new in python.I am reading a Source code and get some doubt.我是 python 新手。我正在阅读源代码并得到一些疑问。

 if config_path:
        logging.info('loading config from %s' % config_path)
        with open(config_path, 'rb') as f:
            try:
                **config = parse_json_in_str(f.read().decode('utf8'))**
            except ValueError as e:
                logging.error('found an error in config.json: %s',
                              e.message)
                sys.exit(1)
    else:
        config = {}

The variable "config" is a string here(parse_json_in_str).Here is the parse_json_in_str:变量“config”在这里是一个字符串(parse_json_in_str)。这里是 parse_json_in_str:

def parse_json_in_str(data):
# parse json and convert everything from unicode to str
return json.loads(data, object_hook=_decode_dict)

And then:进而:

 v_count = 0
    for key, value in optlist:
        if key == '-p':
            config['server_port'] = int(value)
        elif key == '-k':
            config['password'] = to_bytes(value)
        elif key == '-l':
            config['local_port'] = int(value)
        elif key == '-s':
            config['server'] = to_str(value)
        elif key == '-m':
            config['method'] = to_str(value)
        elif key == '-b':
            config['local_address'] = to_str(value)
        elif key == '-v':
            v_count += 1
            # '-vv' turns on more verbose mode
            config['verbose'] = v_count
        elif key == '-t':
            config['timeout'] = int(value)

        .....
        elif key == '-q':
            v_count -= 1
            config['verbose'] = v_count
except getopt.GetoptError as e:
    print(e, file=sys.stderr)
    print_help(is_local)
    sys.exit(2)

why the "config" turn into a dict?为什么“配置”变成了字典?

In this case, json.loads is returning a dictionary ... the json docs say,在这种情况下, json.loads 正在返回一个字典...... json 文档说,

Deserialize s (a str or unicode instance containing a JSON document) to a Python object using this conversion table.使用此转换表将 s(包含 JSON 文档的 str 或 unicode 实例)反序列化为 Python 对象。

And the conversion table says that a json object is converted to a dict .并且转换表说 json 对象转换为dict

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM