【问题标题】:Python: Change list type for json decodingPython:更改 json 解码的列表类型
【发布时间】:2012-06-08 18:12:02
【问题描述】:

在 Python 2.7+ 中,我可以使用内置 json 模块中的object_pairs_hook 来更改解码对象的类型。有没有办法对列表做同样的事情?

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

【问题讨论】:

    标签: python json decode


    【解决方案1】:

    根据源代码,这是不可能的:C 级函数显式实例化内置 list 类型而不使用任何回调/挂钩。后备箱也一样。

    【讨论】:

      【解决方案2】:

      要对列表执行类似操作,您需要继承 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])
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-11-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-06-24
        • 2015-09-28
        • 2021-11-30
        相关资源
        最近更新 更多