Python:更改json解码的列表类型
在Python2.7+中,我可以使用内置json模块中的Python:更改json解码的列表类型,python,json,decode,Python,Json,Decode,在Python2.7+中,我可以使用内置json模块中的object\u pairs\u hook来更改解码对象的类型。对于列表是否也有相同的操作 一种选择是遍历作为钩子参数获取的对象,并用我自己的列表类型替换它们,但是还有其他更智能的方法吗?根据源代码,这是不可能的:C级函数在不使用任何回调/钩子的情况下显式实例化内置的列表类型。trunk中也一样。要对列表执行类似操作,需要对JSONDecoder进行子类化。下面是一个简单的例子,它的工作原理类似于对象对\u钩子。这使用了字符串扫描的纯pyt
object\u pairs\u hook
来更改解码对象的类型。对于列表是否也有相同的操作
一种选择是遍历作为钩子参数获取的对象,并用我自己的列表类型替换它们,但是还有其他更智能的方法吗?根据源代码,这是不可能的:C级函数在不使用任何回调/钩子的情况下显式实例化内置的
列表
类型。trunk中也一样。要对列表执行类似操作,需要对JSONDecoder进行子类化。下面是一个简单的例子,它的工作原理类似于对象对\u钩子
。这使用了字符串扫描的纯python实现,而不是C实现
import json
class decoder(json.JSONDecoder):
def __init__(self, list_type=list, **kwargs):
json.JSONDecoder.__init__(self, **kwargs)
# Use the custom JSONArray
self.parse_array = self.JSONArray
# Use the python implemenation of the scanner
self.scan_once = json.scanner.py_make_scanner(self)
self.list_type=list_type
def JSONArray(self, s_and_end, scan_once, **kwargs):
values, end = json.decoder.JSONArray(s_and_end, scan_once, **kwargs)
return self.list_type(values), end
s = "[1, 2, 3, 4, 3, 2]"
print json.loads(s, cls=decoder) # [1, 2, 3, 4, 3, 2]
print json.loads(s, cls=decoder, list_type=list) # [1, 2, 3, 4, 3, 2]
print json.loads(s, cls=decoder, list_type=set) # set([1, 2, 3, 4])
print json.loads(s, cls=decoder, list_type=tuple) # set([1, 2, 3, 4, 3, 2])