解码json数组为Frozensets

时间:2019-05-15 00:46:02

标签: python json simplejson

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

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})

1 个答案:

答案 0 :(得分:1)

我不熟悉您通过将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}),但是由于集合是无序的,所以没关系。