2017-05-26 176 views
0

我想在字典是JSON反序列化時將以下字典中的整數字符串的鍵轉換爲整數。我試過指定json.loads選項parse_int,但這不起作用。將字符串整數的JSON字典轉換爲整數

>>> d = {'1' : 2, '2':3, "a" : 3} 
>>> json.loads(json.dumps(d), parse_int = int) 
{'2': 3, 'a': 3, '1': 2} 

所需的輸出是{1: 2, 2: 3, 'a': 3}

+0

循環遍歷對象使用...並創建一個新的對象。 在鍵上使用parseInt(),並將返回值用作新對象中的鍵。 – divinemaniac

+0

「parse_int」不適合你的原因是,這些鍵實際上是字符串。 'parse_int'用於解析JSON整數,而不是看起來像整數的JSON字符串。 –

回答

1

如何:

import json 
d = {'1' : 2, '2':3, "a" : 3} 
j = json.loads(json.dumps(d)) 
output_dict = {} 
for k, v in j.items(): 
    try: 
     output_dict[int(k)] = v 
    except ValueError: 
     output_dict[k] = v 

print output_dict 

結果: {u'a': 3, 1: 2, 2: 3}

+0

在您的解決方案中不需要使用'parse_int'。 –

+0

_____fixed_____ – JacobIRR