【发布时间】:2012-06-08 18:12:02
【问题描述】:
在 Python 2.7+ 中,我可以使用内置 json 模块中的object_pairs_hook 来更改解码对象的类型。有没有办法对列表做同样的事情?
一种选择是遍历我作为钩子参数获得的对象并将它们替换为我自己的列表类型,但是还有其他更聪明的方法吗?
【问题讨论】:
在 Python 2.7+ 中,我可以使用内置 json 模块中的object_pairs_hook 来更改解码对象的类型。有没有办法对列表做同样的事情?
一种选择是遍历我作为钩子参数获得的对象并将它们替换为我自己的列表类型,但是还有其他更聪明的方法吗?
【问题讨论】:
根据源代码,这是不可能的:C 级函数显式实例化内置 list 类型而不使用任何回调/挂钩。后备箱也一样。
【讨论】:
要对列表执行类似操作,您需要继承 JSONDecoder。下面是一个类似object_pairs_hook 的简单示例。这使用字符串扫描的纯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])
【讨论】: