55

したがって、私はPython 2.7を使用しており、jsonモジュールを使用して次のデータ構造をエンコードしています。

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

私の問題は、次のように、きれいな印刷を使用してすべてを印刷していることです。

json.dumps(data_structure, indent=2)

中のコンテンツを除いて、すべてをインデントしたい場合を除いて、これは素晴らしいことです"layer3_1"—座標を一覧表示する大規模な辞書であるため、それぞれに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"もしそうなら、誰かが私にどのように教えてもらえますか?

4

10 に答える 10

25

注: この回答のコードjson.dumps()は、JSON形式の文字列を返すコードでのみ機能し、ファイルのようなオブジェクトに直接書き込むコードでは機能しません。「 2次元で書くjson.dump()」という質問への回答で両方で機能する修正バージョンがあります。JSONファイルへのリスト。)

更新しました

以下は、何度か改訂された私の元の回答のバージョンです。JFSebastianの答えの最初のアイデアを機能させる方法を示すためだけに投稿したオリジナルとは異なり、彼のように、オブジェクトのインデントされていない文字列表現を返しました。最新の更新バージョンは、単独でフォーマットされたPythonオブジェクトJSONを返します。

各座標のキーはdict、OPのコメントの1つに従ってソートされた順序で表示されますが、プロセスを駆動sort_keys=Trueする最初の呼び出しでキーワード引数が指定され、json.dumps()途中でオブジェクトのタイプが文字列に変更されない場合に限ります。つまり、「ラップされた」オブジェクトの実際のタイプが維持されるようになりました。

私の投稿の本来の意図を理解していなかったために、多くの人がそれを否定したと思います。そのため、主にその理由で、私は何度か回答を「修正」して改善しました。現在のバージョンは、@ Erik Allikが彼の回答で使用したアイデアのいくつかと、この回答の下のコメントに示されている他のユーザーからの有用なフィードバックを組み合わせた、私の元の回答のハイブリッドです。

次のコードは、Python2.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]
    }
  }
}
于 2012-11-06T13:31:18.383 に答える
14

ボッジですが、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)
于 2012-11-06T11:21:02.813 に答える
11

次の解決策は、Python2.7.xで正しく機能するようです。Python 2.7のカスタムJSONエンコーダーから取得した回避策を使用して、プレーンなJavaScriptコードを挿入し、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=Truejson.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
于 2014-09-19T13:38:22.967 に答える
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)))
于 2016-09-27T16:55:52.660 に答える
2

あなたは試すことができます:

  • インデントしてはいけないリストを次のように置き換えてマークしますNoIndentList

    class NoIndentList(list):
        pass
    
  • json.Encoder.defaultメソッドをオーバーライドして、のインデントされていない文字列表現を生成しNoIndentListます。

    indent1行も取得せずに、リストにキャストして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}

つまり、最初のリストはを使用してシリアル化され[]、すべてのアイテムが1行にあり、2番目のリストはアイテムごとに1行を使用します。

于 2012-11-06T11:21:14.723 に答える
0

このソリューションは、他のソリューションほどエレガントで一般的ではなく、そこから多くを学ぶことはありませんが、迅速かつ簡単です。

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}]
于 2012-11-06T12:11:30.083 に答える
0

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
        }
    ]
}
于 2016-02-19T20:02:29.287 に答える
0

ちなみに、このWebサイトにはJavaScriptが組み込まれており、行が70文字より短い場合にJSON文字列の行フィードを回避します。

http://www.csvjson.com/json_beautifier

( JSON-jsの修正バージョンを使用して実装されました)

「インラインショートアレイ」を選択します

コピーバッファにあるデータをすばやく表示するのに最適です。

于 2016-08-31T23:43:41.980 に答える
0

実際、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]]
于 2018-07-13T15:41:27.020 に答える
0

最高のパフォーマンスコード(10MBのテキストは1秒かかります):

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)を1つの行にマージしようとします。例:

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

にマージされます:

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

注:閉じ括弧の行には、末尾にコンマが含まれている場合があります

于 2021-07-18T06:26:44.207 に答える