将 json 个数组解码为 frozensets

Decode json arrays to frozensets

我有一个嵌套的 json 数组,我想将数组解码为 frozensets 而不是列表。

import json
class FrozensetDecoder(json.JSONDecoder): 
    def default(self, obj): 
        print(obj) 
        if isinstance(obj, list): 
            return frozenset(obj) 
        return obj 
    array = list = default 


In [8]: json.loads('[1,[2],3]', cls=FrozensetDecoder)                                                                                                                                                                                                                                                  
Out[8]: [1, [2], 3]

但是我想要

frozenset({1, frozenset({2}), 3})

我不熟悉您将 arraylist 重新定义为 default 函数所采用的方法。

这里有一些代码可以满足您的需求:

import json
from json import scanner


class MyDecoder(json.JSONDecoder):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        # set up an alternative function for parsing arrays
        self.previous_parse_array = self.parse_array
        self.parse_array = self.json_array_frozenset
        # ensure that the replaced function gets used
        self.scan_once = scanner.py_make_scanner(self)

    def json_array_frozenset(self, s_and_end, scan_once, **kwargs):
        # call the parse_array that would have been used previously
        values, end = self.previous_parse_array(s_and_end, scan_once, **kwargs)
        # return the same result, but turn the `values` into a frozenset
        return frozenset(values), end


data = json.loads('[1,[2],3]', cls=MyDecoder)
print(data)

请注意,结果将是 frozenset({1, 3, frozenset({2})}) 而不是 frozenset({1, frozenset({2}), 3}),但由于集合是无序的,所以这无关紧要。