source

예쁜 프린트 JSON 덤프

bestscript 2023. 2. 8. 19:42

예쁜 프린트 JSON 덤프

이 코드를 사용하여 예쁜 인쇄를 합니다.dictJSON:

import json
d = {'a': 'blah', 'b': 'foo', 'c': [1,2,3]}
print json.dumps(d, indent = 2, separators=(',', ': '))

출력:

{
  "a": "blah",
  "c": [
    1,
    2,
    3
  ],
  "b": "foo"
}

이것은 조금 과하다(각 목록 요소에 대해 줄바꿈!).

다음 구문을 사용하려면 어떤 구문을 사용해야 합니까?

{
  "a": "blah",
  "c": [1, 2, 3],
  "b": "foo"
}

대신?

jsbeautifier를 사용하게 되었습니다.

import jsbeautifier
opts = jsbeautifier.default_options()
opts.indent_size = 2
jsbeautifier.beautify(json.dumps(d), opts)

출력:

{
  "a": "blah",
  "c": [1, 2, 3],
  "b": "foo"
}

몇 년이 지난 후, 저는 빌트인이 내장된 솔루션을 찾았습니다.pprint모듈:

import pprint
d = {'a': 'blah', 'b': 'foo', 'c': [1,2,3]}
pprint.pprint(d)                    # default width=80 so this will be printed in a single line
pprint.pprint(d, width=20)          # here it will be wrapped exactly as expected

출력:

{'a': 'blah',  
 'b': 'foo',  
 'c': [1, 2, 3]}

또 다른 대안은print(json.dumps(d, indent=None, separators=(',\n', ': ')))

출력은 다음과 같습니다.

{"a": "blah",
"c": [1,
2,
3],
"b": "foo"}

https://docs.python.org/2.7/library/json.html#basic-usage의 공식 문서에서는 기본 args는 다음과 같이 기술되어 있습니다.separators=None즉, 실제로는 "디폴트 사용"을 의미합니다.separators=(', ',': ')콤마 구분자는 k/v 쌍과 목록 요소를 구분하지 않습니다.

jsbeautifier가 잘 안 돼서 그냥 표현을 했어요.Json 패턴은 다음과 같습니다.

'{\n    "string": [\n        4,\n        1.0,\n        6,\n        1.0,\n        8,\n        1.0,\n        9,\n        1.0\n    ],\n...'

내가 원하던 것

'{\n    "string": [ 4, 1.0, 6, 1.0, 8, 1.0, 9, 1.0],\n'

그렇게

t = json.dumps(apriori, indent=4)
t = re.sub('\[\n {7}', '[', t)
t = re.sub('(?<!\]),\n {7}', ',', t)
t = re.sub('\n {4}\]', ']', t)
outfile.write(t)

그래서 한 줄(apriori, t, ind=4)이 아니라 5줄로 했어요.

이것도 꽤 신경이 쓰입니다만, 거의 마음에 드는 1대의 라이너를 발견했습니다.

print json.dumps(eval(str(d).replace('[', '"[').replace(']', ']"').replace('(', '"(').replace(')', ')"')), indent=2).replace('\"\\"[', '[').replace(']\\"\"', ']').replace('\"\\"(', '(').replace(')\\"\"', ')')

는 기본적으로 모든 목록 또는 튜플을 문자열로 변환한 다음 들여쓰기와 함께 json.dumps를 사용하여 dict 형식을 지정합니다.그러면 견적서를 삭제하고 완료하면 됩니다!

주의: dict가 아무리 중첩되어 있어도 모든 목록/튜플을 쉽게 변환할 수 있도록 dict를 문자열로 변환합니다.

추신. 파이썬 경찰이 평가 사용으로 날 쫓지 않았으면 좋겠어...(주의해서 사용)

아마도 효율적이지는 않지만, 더 간단한 경우를 고려해보세요(일부는 Python 3에서 테스트되었지만 Python 2에서도 동작할 수 있을 것입니다).

def dictJSONdumps( obj, levels, indentlevels = 0 ):
    import json
    if isinstance( obj, dict ):
        res = []
        for ix in sorted( obj, key=lambda x: str( x )):
            temp = ' ' * indentlevels + json.dumps( ix, ensure_ascii=False ) + ': '
            if levels:
                temp += dictJSONdumps( obj[ ix ], levels-1, indentlevels+1 )
            else:
                temp += json.dumps( obj[ ix ], ensure_ascii=False )
            res.append( temp )
        return '{\n' + ',\n'.join( res ) + '\n}'
    else:
        return json.dumps( obj, ensure_ascii=False )

이것으로, 독자적인 시리얼 라이저를 완전하게 작성할 필요는 없지만, 몇개의 아이디어를 얻을 수 있습니다.제가 좋아하는 들여쓰기 기술을 사용하여 sure_asciii를 하드코딩했습니다만, 파라미터를 추가해 전달하거나, 자신의 것을 하드코딩 하는 등 할 수 있습니다.

언급URL : https://stackoverflow.com/questions/21866774/pretty-print-json-dumps