[英]Decode json arrays to frozensets
我有一個嵌套的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})
我不熟悉您通過重新定義array
和list
作為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})
但是由於集合是無序的,所以沒關系。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.