Python:更改json解码的列表类型

use*_*952 9 python json decode

在Python 2.7+中,我可以使用object_pairs_hook内置的json模块来更改已解码对象的类型.无论如何还要为列表做同样的事情吗?

一种选择是通过我获得的对象作为钩子的参数并用我自己的列表类型替换它们,但是还有其他更聪明的方法吗?

小智 9

要使用列表执行类似操作,您需要继承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])
Run Code Online (Sandbox Code Playgroud)