Skip to main content
 首页 » 编程设计

python之我可以无损恢复 json.dumps() 已转换为字符串的整数键吗

2025年01月19日23落叶无声

考虑这个片段:

>>> import json 
>>> a = {1:'1'} 
>>> json_a = json.dumps(a) 
>>> json.loads(json_a) 
{'1': '1'} 

我的尝试是将 Python 字典传递给 json.dumps(),然后使用 json.loads() 将其取回。但这并没有发生,可能是因为 JSON alays 将键视为字符串。

有没有其他方法可以保留原始 key 类型?

请您参考如下方法:

通过 json.dumps() 将 Python 字典中的整数键转换为符合 JSON 的字符串键是有损:一旦完成,就无法判断是否原始 key 是整数 23 或字符串 '23'(除非该信息存储在其他地方)。

也就是说,您可以强制json.loads()尽可能将键转换为整数,方法是将适当的函数作为object_pairs_hook传递。参数:

 def int_keys(ordered_pairs): 
    result = {} 
    for key, value in ordered_pairs: 
        try: 
            key = int(key) 
        except ValueError: 
            pass 
        result[key] = value 
    return result 

用法:

>>> import json 
>>> data = {1: '1', 2: '2', 3: '3'} 
>>> text = json.dumps(data) 
>>> text 
'{"1": "1", "2": "2", "3": "3"}' 
>>> json.loads(text, object_pairs_hook=int_keys) 
{1: '1', 2: '2', 3: '3'} 

对此进行扩展,还可以编写一个 object_pairs_hook,它不仅可以转换整数,还可以转换 json.dumps() 可能具有的所有其他非字符串键转换为字符串:

SPECIAL = { 
    "true": True, 
    "false": False, 
    "null": None, 
} 
 
def round_trip(ordered_pairs): 
    result = {} 
    for key, value in ordered_pairs: 
        if key in SPECIAL: 
            key = SPECIAL[key] 
        else: 
            for numeric in int, float: 
                try: 
                    key = numeric(key) 
                except ValueError: 
                    continue 
                else: 
                    break 
        result[key] = value 

用法:

>>> print(more_text) 
{ 
  "2": 2, 
  "3.45": 3.45, 
  "true": true, 
  "false": false, 
  "null": null, 
  "Infinity": Infinity, 
  "-Infinity": -Infinity, 
  "NaN": NaN 
} 
>>> json.loads(more_text, object_pairs_hook=round_trip) 
{2: 2, 3.45: 3.45, True: True, False: False, None: None, inf: inf, -inf: -inf, nan: nan}