2017-09-28 24 views
-1

我是一個新的python.I讀取源代碼並得到一些疑問。在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 = {} 

變量 「配置」 是這裏的字符串(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) 

然後:

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) 

爲什麼 「配置」 變成字典?

+3

沒有'parse_json_in_str'我們無法理解代碼;但我想它是這麼做的:在一個字符串中解析一些JSON並返回解析的值;在這種情況下,這似乎是一個字典。 – bfontaine

+0

parse_json_in_str prolly需要一個字符串並返回一個字典?不知道沒有看到它。 – Jacobr365

+0

謝謝,bfontaine。 – zhan

回答

0

在這種情況下,json.loads返回一個字典... the json docs說,

反序列化S(一個STR或含有JSON文檔的unicode實例)使用該轉換表Python對象。

conversion table說,JSON對象被轉換爲dict

相關問題