【问题标题】:Python JSONDecoder custom translation of null typePython JSONDecoder 自定义翻译 null 类型
【发布时间】:2015-02-26 01:18:23
【问题描述】:

在 python 中,JSONDecoder 默认将 null 转换为 None,如下所示。如何将 null -> None 的翻译更改为不同的内容。即 null -> 'Cat'

class json.JSONDecoder([encoding[, object_hook[, parse_float[, parse_int[, parse_constant[, strict[, object_pairs_hook]]]]]]])

Simple JSON decoder.

Performs the following translations in decoding by default:
  JSON  Python
  object    dict
  array     list
  string    unicode
  number (int)  int, long
  number (real)     float
  true  True
  false     False
  null  None

我想要 json.loads({"field1":null, "field2": "data!"})

返回 {u'field2': u'data!', u'field1': u'Cat'}

【问题讨论】:

  • 你能否在解码 JSON 后直接浏览dict.values(),然后将None 转换为'Cat'?如果没有,请参阅:taketwoprogramming.blogspot.com/2009/06/…
  • mattm 我可以在翻译完所有值后直接浏览它们,但希望避免对每个值进行额外的比较处理。我想以某种方式扩展 JSONDecoder 以将初始翻译更改为仅处理从“无”到“猫”的切换
  • for key in old_dict: old_dict[key] = 'Cat' if old_dict[key] == None 之后马上做这件事一点也不坏。

标签: python json decode translate


【解决方案1】:

2014 年 12 月 30 日更新

实现这一点的最简单方法是使用JSONDecoder 的object_hook 回调,如下面的旧答案所述。但是,由于这需要对数据中的每个键值对进行额外的函数调用,因此可能会对性能产生影响。

所以,如果你真的想改变 json 处理 None 的方式,你需要更深入地挖掘。 JSONDecoder 使用扫描器在 JSON 输入中查找某些标记。不幸的是,这是一个函数而不是一个类,因此子类化并不容易。扫描器函数称为py_make_scanner,可以在 json/scanner.py 中找到。它基本上是一个以 JSONDecoder 作为参数并返回 scan_once 函数的函数。 scan_once 函数接收一个字符串和一个当前扫描仪位置的索引。

一个简单的自定义扫描仪功能可能如下所示:

import json

def make_my_scanner(context):
    # reference to actual scanner
    interal_scanner = json.scanner.py_make_scanner(context)

    # some references for the _scan_once function below
    parse_object = context.parse_object
    parse_array = context.parse_array
    parse_string = context.parse_string
    encoding = context.encoding
    strict = context.strict
    object_hook = context.object_hook
    object_pairs_hook = context.object_pairs_hook

    # customized _scan_once
    def _scan_once(string, idx):
        try:
            nextchar = string[idx]
        except IndexError:
            raise StopIteration

        # override some parse_** calls with the correct _scan_once
        if nextchar == '"':
            return parse_string(string, idx + 1, encoding, strict)
        elif nextchar == '{':
            return parse_object((string, idx + 1), encoding, strict,
                _scan_once, object_hook, object_pairs_hook)
        elif nextchar == '[':
            return parse_array((string, idx + 1), _scan_once)
        elif nextchar == 'n' and string[idx:idx + 4] == 'null':
            return 'Cat', idx + 4

        # invoke default scanner
        return interal_scanner(string, idx)

    return _scan_once

现在我们只需要一个JSONDecoder 子类,它将使用我们的扫描仪而不是默认扫描仪:

class MyJSONDecoder(json.JSONDecoder):
    def __init__(self, encoding=None, object_hook=None, parse_float=None,
            parse_int=None, parse_constant=None, strict=True,
            object_pairs_hook=None):

        json.JSONDecoder.__init__(self, encoding, object_hook, parse_float, parse_int, parse_constant, strict, object_pairs_hook)

        # override scanner
        self.scan_once = make_my_scanner(self)

然后像这样使用它:

decoder = MyJSONDecoder()
print decoder.decode('{"field1":null, "field2": "data!"}')

旧答案,但如果您不关心另一个函数调用的性能影响,它仍然有效:

您需要使用特殊的object_hook 方法创建一个JSONDecoder 对象:

import json

def parse_object(o):
    for key in o:
        if o[key] is None:
            o[key] = 'Cat'
    return o

decoder = json.JSONDecoder(object_hook=parse_object)

print decoder.decode('{"field1":null, "field2": "data!"}')
# that will print: {u'field2': u'data!', u'field1': u'Cat'}

根据Python documentation of the json module:

object_hook 是一个可选函数,将使用解码的任何对象字面量(一个字典)的结果调用。将使用 object_hook 的返回值而不是 dict。

所以parse_object 将获得一个可以通过将所有None 值与“Cat”交换来操作的字典。然后将在输出中使用返回的对象/字典。

【讨论】:

  • Timo D,这是一个很好的解决方案,但不完全是我想要完成的。在 JSONDecoder 中的初始翻译期间,有一个将“null”等同于“None”的映射,我想通过以某种方式扩展 JSONDecoder 来更改该映射。最初使用自定义翻译比使用 object_hook 进行后处理具有性能优势。我假设在初始转换发生更改“null”->“Cat”之后调用 object_hook 函数。那么如何通过扩展 JSONDecoder 来改变翻译规则呢?
  • 公平地说,我更新了我的答案以包含一种不应该影响性能的方法
  • Timo D,非常好的解释,谢谢。很高兴看到如何指定自定义扫描仪,这开启了一个充满可能性的新世界。
猜你喜欢
  • 2021-08-21
  • 1970-01-01
  • 1970-01-01
  • 2013-05-17
  • 2016-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-29
相关资源
最近更新 更多