【问题标题】:How to implement custom indentation when pretty-printing with the JSON module?使用 JSON 模块进行漂亮打印时如何实现自定义缩进?
【发布时间】:2012-10-26 07:27:04
【问题描述】:

所以我使用 Python 2.7,使用 json 模块对以下数据结构进行编码:

'layer1': {
    'layer2': {
        'layer3_1': [ long_list_of_stuff ],
        'layer3_2': 'string'
    }
}

我的问题是我正在使用漂亮的打印来打印所有内容,如下所示:

json.dumps(data_structure, indent=2)

这很好,除了我想缩进所有内容,除了 "layer3_1" 中的内容——这是一个列出坐标的庞大字典,因此,在每个坐标上设置一个值可以让漂亮的打印创建一个文件上千行,举个例子如下:

{
  "layer1": {
    "layer2": {
      "layer3_1": [
        {
          "x": 1,
          "y": 7
        },
        {
          "x": 0,
          "y": 4
        },
        {
          "x": 5,
          "y": 3
        },
        {
          "x": 6,
          "y": 9
        }
      ],
      "layer3_2": "string"
    }
  }
}

我真正想要的是类似于以下内容:

{
  "layer1": {
    "layer2": {
      "layer3_1": [{"x":1,"y":7},{"x":0,"y":4},{"x":5,"y":3},{"x":6,"y":9}],
      "layer3_2": "string"
    }
  }
}

我听说可以扩展 json 模块:是否可以将其设置为仅在 "layer3_1" 对象内时关闭缩进?如果是这样,有人能告诉我怎么做吗?

【问题讨论】:

  • 你的第一个代码 sn-p 既不是 JSON 也不是 Python。
  • 缩进是印刷的问题,而不是表示的问题。
  • 对于“漂亮的打印”,您的意思是您正在使用pprint 模块?
  • 将第一个 sn-p 修改为可识别的内容。我正在使用json.dumps(data_structure, indent=2) - 作为示例添加。
  • 我已经发布了一个适用于 2.7 的解决方案,并且可以很好地与 sort_keys 等选项配合使用,并且没有针对排序顺序的特殊情况实现,而是依赖于(组合)collections.OrderedDict

标签: python json indentation


【解决方案1】:

一个好主意,但是一旦你从 dumps() 中得到字符串,你可以对其执行正则表达式替换,如果你确定它的内容格式的话。大致如下:

s = json.dumps(data_structure, indent=2)
s = re.sub('\s*{\s*"(.)": (\d+),\s*"(.)": (\d+)\s*}(,?)\s*', r'{"\1":\2,"\3":\4}\5', s)

【讨论】:

  • 谢谢,这也有效,而且确实更小,但决定采用@martineau 提供的解决方案
  • 您的解决方案非常有趣!:) 我喜欢它,它不需要任何“NoIdent”标记,开箱即用。明天我可能会针对大型输入文件对其进行测试,我正在寻找一个简单的解决方案来打破 csv 世界,因为它实际上不允许元数据,但要保持可读性。
【解决方案2】:

你可以试试:

  • 将不应该缩进的列表标记为NoIndentList

    class NoIndentList(list):
        pass
    
  • 覆盖json.Encoder.default method 以生成NoIndentList 的非缩进字符串表示。

    您可以将其转换回列表并在没有indent 的情况下调用 json.dumps() 以获得单行

上述方法似乎不适用于 json 模块:

import json
import sys

class NoIndent(object):
    def __init__(self, value):
        self.value = value

def default(o, encoder=json.JSONEncoder()):
    if isinstance(o, NoIndent):
        return json.dumps(o.value)
    return encoder.default(o)

L = [dict(x=x, y=y) for x in range(1) for y in range(2)]
obj = [NoIndent(L), L]
json.dump(obj, sys.stdout, default=default, indent=4)

它产生无效的输出(列表被序列化为字符串):

[
    "[{\"y\": 0, \"x\": 0}, {\"y\": 1, \"x\": 0}]", 
    [
        {
            "y": 0, 
            "x": 0
        }, 
        {
            "y": 1, 
            "x": 0
        }
    ]
]

如果您可以使用yaml,则该方法有效:

import sys
import yaml

class NoIndentList(list):
    pass

def noindent_list_presenter(dumper, data):
    return dumper.represent_sequence(u'tag:yaml.org,2002:seq', data,
                                     flow_style=True)
yaml.add_representer(NoIndentList, noindent_list_presenter)


obj = [
    [dict(x=x, y=y) for x in range(2) for y in range(1)],
    [dict(x=x, y=y) for x in range(1) for y in range(2)],
    ]
obj[0] = NoIndentList(obj[0])
yaml.dump(obj, stream=sys.stdout, indent=4)

它产生:

- [{x: 0, y: 0}, {x: 1, y: 0}]
-   - {x: 0, y: 0}
    - {x: 0, y: 1}

即,第一个列表使用[] 进行序列化,并且所有项目都在一行上,第二个列表每个项目使用一行。

【讨论】:

  • 我想我明白了你所说的一半,尽管我有点困惑。可能取决于我之前不必重写 Python 中的方法。我会做更多的阅读,但如果你能提供一个更完整的例子,将不胜感激!
【解决方案3】:

此解决方案不像其他解决方案那样优雅和通用,您不会从中学到很多东西,但它快速而简单。

def custom_print(data_structure, indent):
    for key, value in data_structure.items():
        print "\n%s%s:" % (' '*indent,str(key)),
        if isinstance(value, dict):
            custom_print(value, indent+1)
        else:
            print "%s" % (str(value)),

使用和输出:

>>> custom_print(data_structure,1)

 layer1:
  layer2:
   layer3_2: string
   layer3_1: [{'y': 7, 'x': 1}, {'y': 4, 'x': 0}, {'y': 3, 'x': 5}, {'y': 9, 'x': 6}]

【讨论】:

    【解决方案4】:

    (注意: 此答案中的代码仅适用于 json.dumps(),它返回 JSON 格式的字符串,但 notjson.dump() 直接写入类似文件的对象。在我对问题Write two-dimensional list to JSON file 的回答中,它有一个修改版本适用于两者。)

    更新

    以下是我的原始答案的一个版本,经过多次修改。与原版不同,我发布它只是为了展示如何让 J.F.Sebastian 的answer 中的第一个想法起作用,并且像他的一样,返回对象的非缩进 string 表示。最新更新的版本返回单独格式化的 Python 对象 JSON。

    每个坐标 dict 的键将按照 OP 的 cmets 之一按排序顺序出现,但前提是在驱动进程的初始 json.dumps() 调用中指定了 sort_keys=True 关键字参数,并且它没有沿途将对象的类型更改为字符串。换句话说,“包装”对象的实际类型现在得到了维护。

    我认为不理解我的帖子的初衷导致很多人对其投反对票 - 因此,主要出于这个原因,我已经“修复”并改进了我的答案几次。当前版本是我的原始答案与@Erik Allik 在他的answer 中使用的一些想法的混合体,以及此答案下方的 cmets 中显示的其他用户的有用反馈。

    以下代码在 Python 2.7.16 和 3.7.4 中似乎都没有改变。

    from _ctypes import PyObj_FromPtr
    import json
    import re
    
    class NoIndent(object):
        """ Value wrapper. """
        def __init__(self, value):
            self.value = value
    
    
    class MyEncoder(json.JSONEncoder):
        FORMAT_SPEC = '@@{}@@'
        regex = re.compile(FORMAT_SPEC.format(r'(\d+)'))
    
        def __init__(self, **kwargs):
            # Save copy of any keyword argument values needed for use here.
            self.__sort_keys = kwargs.get('sort_keys', None)
            super(MyEncoder, self).__init__(**kwargs)
    
        def default(self, obj):
            return (self.FORMAT_SPEC.format(id(obj)) if isinstance(obj, NoIndent)
                    else super(MyEncoder, self).default(obj))
    
        def encode(self, obj):
            format_spec = self.FORMAT_SPEC  # Local var to expedite access.
            json_repr = super(MyEncoder, self).encode(obj)  # Default JSON.
    
            # Replace any marked-up object ids in the JSON repr with the
            # value returned from the json.dumps() of the corresponding
            # wrapped Python object.
            for match in self.regex.finditer(json_repr):
                # see https://stackoverflow.com/a/15012814/355230
                id = int(match.group(1))
                no_indent = PyObj_FromPtr(id)
                json_obj_repr = json.dumps(no_indent.value, sort_keys=self.__sort_keys)
    
                # Replace the matched id string with json formatted representation
                # of the corresponding Python object.
                json_repr = json_repr.replace(
                                '"{}"'.format(format_spec.format(id)), json_obj_repr)
    
            return json_repr
    
    
    if __name__ == '__main__':
        from string import ascii_lowercase as letters
    
        data_structure = {
            'layer1': {
                'layer2': {
                    'layer3_1': NoIndent([{"x":1,"y":7}, {"x":0,"y":4}, {"x":5,"y":3},
                                          {"x":6,"y":9},
                                          {k: v for v, k in enumerate(letters)}]),
                    'layer3_2': 'string',
                    'layer3_3': NoIndent([{"x":2,"y":8,"z":3}, {"x":1,"y":5,"z":4},
                                          {"x":6,"y":9,"z":8}]),
                    'layer3_4': NoIndent(list(range(20))),
                }
            }
        }
    
        print(json.dumps(data_structure, cls=MyEncoder, sort_keys=True, indent=2))
    

    输出:

    {
      "layer1": {
        "layer2": {
          "layer3_1": [{"x": 1, "y": 7}, {"x": 0, "y": 4}, {"x": 5, "y": 3}, {"x": 6, "y": 9}, {"a": 0, "b": 1, "c": 2, "d": 3, "e": 4, "f": 5, "g": 6, "h": 7, "i": 8, "j": 9, "k": 10, "l": 11, "m": 12, "n": 13, "o": 14, "p": 15, "q": 16, "r": 17, "s": 18, "t": 19, "u": 20, "v": 21, "w": 22, "x": 23, "y": 24, "z": 25}],
          "layer3_2": "string",
          "layer3_3": [{"x": 2, "y": 8, "z": 3}, {"x": 1, "y": 5, "z": 4}, {"x": 6, "y": 9, "z": 8}],
          "layer3_4": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
        }
      }
    }
    

    【讨论】:

    • 很好,我得到了这个工作,但为了虚荣心想对 x 和 y 进行排序(生成的部分 JSON 需要稍后手动编辑,不要问为什么 :(),所以我尝试使用OrderedDict。现在我的问题是我在输出中得到以下内容:"layer3_1": "[OrderedDict([('x', 804), ('y', 622)]), OrderedDict([('x', 817), ('y', 635)]), OrderedDict([('x', 817), ('y', 664)]), OrderedDict([('x', 777), (' y', 664)]), OrderedDict([('x', 777), ('y', 622)]), OrderedDict([('x', 804), ('y' , 622)])]", 我想我错过了一些东西......
    • 这仍然将列表打印为字符串。
    • @ErikAllik 完全正确。该列表变成了一个字符串:"[{'x':1, 'y':7}, {'x':0, 'y':4}, {'x':5, 'y':3}, {'x':6, 'y':9}]"。这是一个错误的答案!
    • 由于使用单引号,无法使用反序列化 (json.loads())。我必须改用@ErikAllik 的答案。 -- github.com/patarapolw/pyexcel-formatter/blob/master/…
    • @Polv:感谢您的反馈。我已经更新了我的答案来解决这个问题。
    【解决方案5】:

    以下解决方案似乎在 Python 2.7.x 上正常工作。它使用取自 Custom JSON encoder in Python 2.7 to insert plain JavaScript code 的解决方法,通过使用基于 UUID 的替换方案,避免自定义编码对象在输出中最终成为 JSON 字符串。

    class NoIndent(object):
        def __init__(self, value):
            self.value = value
    
    
    class NoIndentEncoder(json.JSONEncoder):
        def __init__(self, *args, **kwargs):
            super(NoIndentEncoder, self).__init__(*args, **kwargs)
            self.kwargs = dict(kwargs)
            del self.kwargs['indent']
            self._replacement_map = {}
    
        def default(self, o):
            if isinstance(o, NoIndent):
                key = uuid.uuid4().hex
                self._replacement_map[key] = json.dumps(o.value, **self.kwargs)
                return "@@%s@@" % (key,)
            else:
                return super(NoIndentEncoder, self).default(o)
    
        def encode(self, o):
            result = super(NoIndentEncoder, self).encode(o)
            for k, v in self._replacement_map.iteritems():
                result = result.replace('"@@%s@@"' % (k,), v)
            return result
    

    那么这个

    obj = {
      "layer1": {
        "layer2": {
          "layer3_2": "string", 
          "layer3_1": NoIndent([{"y": 7, "x": 1}, {"y": 4, "x": 0}, {"y": 3, "x": 5}, {"y": 9, "x": 6}])
        }
      }
    }
    print json.dumps(obj, indent=2, cls=NoIndentEncoder)
    

    产生以下输出:

    {
      "layer1": {
        "layer2": {
          "layer3_2": "string", 
          "layer3_1": [{"y": 7, "x": 1}, {"y": 4, "x": 0}, {"y": 3, "x": 5}, {"y": 9, "x": 6}]
        }
      }
    }
    

    它还正确传递了所有选项(indent 除外),例如sort_keys=True 到嵌套的 json.dumps 调用。

    obj = {
        "layer1": {
            "layer2": {
                "layer3_1": NoIndent([{"y": 7, "x": 1, }, {"y": 4, "x": 0}, {"y": 3, "x": 5, }, {"y": 9, "x": 6}]),
                "layer3_2": "string",
            }
        }
    }    
    print json.dumps(obj, indent=2, sort_keys=True, cls=NoIndentEncoder)
    

    正确输出

    {
      "layer1": {
        "layer2": {
          "layer3_1": [{"x": 1, "y": 7}, {"x": 0, "y": 4}, {"x": 5, "y": 3}, {"x": 6, "y": 9}], 
          "layer3_2": "string"
        }
      }
    }
    

    它也可以与例如collections.OrderedDict:

    obj = {
        "layer1": {
            "layer2": {
                "layer3_2": "string",
                "layer3_3": NoIndent(OrderedDict([("b", 1), ("a", 2)]))
            }
        }
    }
    print json.dumps(obj, indent=2, cls=NoIndentEncoder)
    

    输出

    {
      "layer1": {
        "layer2": {
          "layer3_3": {"b": 1, "a": 2}, 
          "layer3_2": "string"
        }
      }
    }
    

    更新:在 Python 3 中,没有 iteritems。你可以用这个替换encode

    def encode(self, o):
        result = super(NoIndentEncoder, self).encode(o)
        for k, v in iter(self._replacement_map.items()):
            result = result.replace('"@@%s@@"' % (k,), v)
        return result
    

    【讨论】:

    • 对于那些不了解此解决方案如何工作的人:for k, v in self._replacement_map.iteritems(): result = result.replace('"@@%s@@"' % (k,), v) 内的两行 encode(),是将 "layer3_1": "@@d4e06719f9cb420a82ace98becab5ff8@@" 替换为 "layer3_1": [{"y": 7, "x": 1}, {"y": 4, "x": 0}, {"y": 3, "x": 5}, {"y": 9, "x": 6}]。我认为这个解决方案在某种意义上等同于@M Somerville 的重新替换解决方案。
    • 这也适用于 Python 3。唯一需要注意的是您必须使用 json.dumps,而不是 json.dump!在后一种情况下,您还必须覆盖 iterencode(),而我无法使其正常工作。
    【解决方案6】:

    如果您有太多不同类型的对象对 JSON 有贡献而无法尝试使用 JSONEncoder 方法,并且有太多不同类型无法使用正则表达式,那么这里有一个后处理解决方案。此函数在指定级别后折叠空白,而无需知道数据本身的细节。

    def collapse_json(text, indent=12):
        """Compacts a string of json data by collapsing whitespace after the
        specified indent level
    
        NOTE: will not produce correct results when indent level is not a multiple
        of the json indent level
        """
        initial = " " * indent
        out = []  # final json output
        sublevel = []  # accumulation list for sublevel entries
        pending = None  # holder for consecutive entries at exact indent level
        for line in text.splitlines():
            if line.startswith(initial):
                if line[indent] == " ":
                    # found a line indented further than the indent level, so add
                    # it to the sublevel list
                    if pending:
                        # the first item in the sublevel will be the pending item
                        # that was the previous line in the json
                        sublevel.append(pending)
                        pending = None
                    item = line.strip()
                    sublevel.append(item)
                    if item.endswith(","):
                        sublevel.append(" ")
                elif sublevel:
                    # found a line at the exact indent level *and* we have sublevel
                    # items. This means the sublevel items have come to an end
                    sublevel.append(line.strip())
                    out.append("".join(sublevel))
                    sublevel = []
                else:
                    # found a line at the exact indent level but no items indented
                    # further, so possibly start a new sub-level
                    if pending:
                        # if there is already a pending item, it means that
                        # consecutive entries in the json had the exact same
                        # indentation and that last pending item was not the start
                        # of a new sublevel.
                        out.append(pending)
                    pending = line.rstrip()
            else:
                if pending:
                    # it's possible that an item will be pending but not added to
                    # the output yet, so make sure it's not forgotten.
                    out.append(pending)
                    pending = None
                if sublevel:
                    out.append("".join(sublevel))
                out.append(line)
        return "\n".join(out)
    

    例如,使用此结构作为缩进级别为 4 的 json.dumps 的输入:

    text = json.dumps({"zero": ["first", {"second": 2, "third": 3, "fourth": 4, "items": [[1,2,3,4], [5,6,7,8], 9, 10, [11, [12, [13, [14, 15]]]]]}]}, indent=4)
    

    这是函数在不同缩进级别的输出:

    >>> print collapse_json(text, indent=0)
    {"zero": ["first", {"items": [[1, 2, 3, 4], [5, 6, 7, 8], 9, 10, [11, [12, [13, [14, 15]]]]], "second": 2, "fourth": 4, "third": 3}]}
    >>> print collapse_json(text, indent=4)
    {
        "zero": ["first", {"items": [[1, 2, 3, 4], [5, 6, 7, 8], 9, 10, [11, [12, [13, [14, 15]]]]], "second": 2, "fourth": 4, "third": 3}]
    }
    >>> print collapse_json(text, indent=8)
    {
        "zero": [
            "first",
            {"items": [[1, 2, 3, 4], [5, 6, 7, 8], 9, 10, [11, [12, [13, [14, 15]]]]], "second": 2, "fourth": 4, "third": 3}
        ]
    }
    >>> print collapse_json(text, indent=12)
    {
        "zero": [
            "first", 
            {
                "items": [[1, 2, 3, 4], [5, 6, 7, 8], 9, 10, [11, [12, [13, [14, 15]]]]],
                "second": 2,
                "fourth": 4,
                "third": 3
            }
        ]
    }
    >>> print collapse_json(text, indent=16)
    {
        "zero": [
            "first", 
            {
                "items": [
                    [1, 2, 3, 4],
                    [5, 6, 7, 8],
                    9,
                    10,
                    [11, [12, [13, [14, 15]]]]
                ], 
                "second": 2, 
                "fourth": 4, 
                "third": 3
            }
        ]
    }
    

    【讨论】:

      【解决方案7】:

      附带说明,该网站有一个内置的 JavaScript,当行短于 70 个字符时,该 JavaScript 将避免 JSON 字符串中的换行:

      http://www.csvjson.com/json_beautifier

      (使用JSON-js的修改版本实现)

      选择“内联短数组”

      非常适合快速查看复制缓冲区中的数据。

      【讨论】:

      • 问题是,如何在Python中实现“内联短数组”?
      【解决方案8】:

      这会产生 OP 的预期结果:

      import json
      
      class MyJSONEncoder(json.JSONEncoder):
      
        def iterencode(self, o, _one_shot=False):
          list_lvl = 0
          for s in super(MyJSONEncoder, self).iterencode(o, _one_shot=_one_shot):
            if s.startswith('['):
              list_lvl += 1
              s = s.replace('\n', '').rstrip()
            elif 0 < list_lvl:
              s = s.replace('\n', '').rstrip()
              if s and s[-1] == ',':
                s = s[:-1] + self.item_separator
              elif s and s[-1] == ':':
                s = s[:-1] + self.key_separator
            if s.endswith(']'):
              list_lvl -= 1
            yield s
      
      o = {
        "layer1":{
          "layer2":{
            "layer3_1":[{"y":7,"x":1},{"y":4,"x":0},{"y":3,"x":5},{"y":9,"x":6}],
            "layer3_2":"string",
            "layer3_3":["aaa\nbbb","ccc\nddd",{"aaa\nbbb":"ccc\nddd"}],
            "layer3_4":"aaa\nbbb",
          }
        }
      }
      
      jsonstr = json.dumps(o, indent=2, separators=(',', ':'), sort_keys=True,
          cls=MyJSONEncoder)
      print(jsonstr)
      o2 = json.loads(jsonstr)
      print('identical objects: {}'.format((o == o2)))
      

      【讨论】:

        【解决方案9】:

        确实,YAML 比 JSON 更好的一件事。

        我无法让 NoIndentEncoder 工作...,但我可以在 JSON 字符串上使用正则表达式...

        def collapse_json(text, list_length=5):
            for length in range(list_length):
                re_pattern = r'\[' + (r'\s*(.+)\s*,' * length)[:-1] + r'\]'
                re_repl = r'[' + ''.join(r'\{}, '.format(i+1) for i in range(length))[:-2] + r']'
        
                text = re.sub(re_pattern, re_repl, text)
        
            return text
        

        问题是,如何在嵌套列表上执行此操作?

        之前:

        [
          0,
          "any",
          [
            2,
            3
          ]
        ]
        

        之后:

        [0, "any", [2, 3]]
        

        【讨论】:

          【解决方案10】:

          最佳性能代码(10MB 文本花费 1s):

          import json
          def dumps_json(data, indent=2, depth=2):
              assert depth > 0
              space = ' '*indent
              s = json.dumps(data, indent=indent)
              lines = s.splitlines()
              N = len(lines)
              # determine which lines to be shortened
              is_over_depth_line = lambda i: i in range(N) and lines[i].startswith(space*(depth+1))
              is_open_bracket_line = lambda i: not is_over_depth_line(i) and is_over_depth_line(i+1)
              is_close_bracket_line = lambda i: not is_over_depth_line(i) and is_over_depth_line(i-1)
              # 
              def shorten_line(line_index):
                  if not is_open_bracket_line(line_index):
                      return lines[line_index]
                  # shorten over-depth lines
                  start = line_index
                  end = start
                  while not is_close_bracket_line(end):
                      end += 1
                  has_trailing_comma = lines[end][-1] == ','
                  _lines = [lines[start][-1], *lines[start+1:end], lines[end].replace(',','')]
                  d = json.dumps(json.loads(' '.join(_lines)))
                  return lines[line_index][:-1] + d + (',' if has_trailing_comma else '')
              # 
              s = '\n'.join([
                  shorten_line(i)
                  for i in range(N) if not is_over_depth_line(i) and not is_close_bracket_line(i)
              ])
              #
              return s
          

          更新: 这是我的解释:

          首先我们使用 json.dumps 来获取 json 字符串已经缩进。 示例:

          >>>  print(json.dumps({'0':{'1a':{'2a':None,'2b':None},'1b':{'2':None}}}, indent=2))
          [0]  {
          [1]    "0": {
          [2]      "1a": {
          [3]        "2a": null,
          [4]        "2b": null
          [5]      },
          [6]      "1b": {
          [7]        "2": null
          [8]      }
          [9]    }
          [10] }
          

          如果我们设置indent=2depth = 2,那么太深的行以6 个空格开头

          我们有 4 种类型的线:

          1. 法线
          2. 左括号线 (2,6)
          3. 超过深度线 (3,4,7)
          4. 右括号线 (5,8)

          我们将尝试将一系列行(类型 2 + 3 + 4)合并为一行。 示例:

          [2]      "1a": {
          [3]        "2a": null,
          [4]        "2b": null
          [5]      },
          

          将被合并到:

          [2]      "1a": {"2a": null, "2b": null},
          

          注意:右括号行可能有尾随逗号

          【讨论】:

          • 但是,他们没有询问速度和性能!请解释更多。
          • 我必须统计一个庞大的数据指标。所以我只关注性能和准确性。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-07-30
          • 2016-11-30
          • 1970-01-01
          • 2012-10-04
          • 2020-01-12
          相关资源
          最近更新 更多