개발/Python

JSON 파일을 예쁜 인쇄하는 방법?

MinorMan 2020. 9. 18. 03:42
반응형

<질문>

내가 prettyprint하고 싶은 엉망인 JSON 파일이 있습니다. 파이썬에서 이것을하는 가장 쉬운 방법은 무엇입니까?

PrettyPrint가 파일이라고 생각하는 "객체"를 사용한다는 것을 알고 있지만 파일을 전달하는 방법을 모르겠습니다. 파일 이름 만 사용하면 작동하지 않습니다.


<답변1>

json 모듈은 이미 들여 쓰기 할 공백 수를 지정하는 indent 매개 변수를 사용하여 몇 가지 기본적인 예쁜 인쇄를 구현합니다.

>>> import json
>>>
>>> your_json = '["foo", {"bar":["baz", null, 1.0, 2]}]'
>>> parsed = json.loads(your_json)
>>> print(json.dumps(parsed, indent=4, sort_keys=True))
[
    "foo", 
    {
        "bar": [
            "baz", 
            null, 
            1.0, 
            2
        ]
    }
]

파일을 구문 분석하려면 json.load ()를 사용하십시오.

with open('filename.txt', 'r') as handle:
    parsed = json.load(handle)

<답변2>

명령 줄에서이 작업을 수행 할 수 있습니다.

python3 -m json.tool some.json

(이미 질문에 대한 주석에서 언급했듯이 python3 제안에 대한 @Kai Petzke 덕분에).

실제로 파이썬은 명령 줄에서 json 처리에 관한 한 제가 가장 좋아하는 도구가 아닙니다. 단순한 예쁜 인쇄의 경우 괜찮지 만 json을 조작하려면 지나치게 복잡해질 수 있습니다. 곧 별도의 스크립트 파일을 작성해야합니다. 키가 u "some-key"(python unicode) 인 맵으로 끝날 수 있습니다.이 맵은 필드 선택을 더 어렵게 만들고 실제로 예쁜 방향으로 가지 않습니다. -인쇄.

jq를 사용할 수도 있습니다.

jq . some.json

그리고 당신은 보너스로 색상을 얻습니다 (그리고 훨씬 더 쉬운 확장 성).

부록 : 한편으로는 큰 JSON 파일을 처리하기 위해 jq를 사용하고 다른 한편으로는 매우 큰 jq 프로그램을 사용하는 것에 대한 의견에 약간의 혼란이 있습니다. 하나의 큰 JSON 엔티티로 구성된 파일을 예쁘게 인쇄하는 경우 실제 제한은 RAM입니다. 실제 데이터의 단일 배열로 구성된 2GB 파일을 pretty-printing하는 경우 pretty-printing에 필요한 "최대 상주 세트 크기"는 5GB (jq 1.5 또는 1.6 사용 여부)였습니다. 또한 jq는 pip install jq 후 python 내에서 사용할 수 있습니다.


<답변3>

내장 모듈 pprint (https://docs.python.org/3.6/library/pprint.html)를 사용할 수 있습니다.

json 데이터로 파일을 읽고 인쇄하는 방법.

import json
import pprint

json_data = None
with open('file_name.txt', 'r') as f:
    data = f.read()
    json_data = json.loads(data)

pprint.pprint(json_data)

<답변4>

Pygmentize는 킬러 도구입니다. 이것 좀 봐.

python json.tool을 pygmentize와 결합합니다.

echo '{"foo": "bar"}' | python -m json.tool | pygmentize -l json

pygmentize 설치 지침은 위의 링크를 참조하십시오.

이에 대한 데모는 아래 이미지에 있습니다.


<답변5>

이 함수를 사용하면 JSON이 str인지 dict인지 기억할 필요가 없습니다. 예쁘게 인쇄 된 것을보세요.

import json

def pp_json(json_thing, sort=True, indents=4):
    if type(json_thing) is str:
        print(json.dumps(json.loads(json_thing), sort_keys=sort, indent=indents))
    else:
        print(json.dumps(json_thing, sort_keys=sort, indent=indents))
    return None

pp_json(your_json_string_or_dict)

<답변6>

명령 줄에서 예쁘게 인쇄하고 들여 쓰기 등을 제어 할 수 있으려면 다음과 유사한 별칭을 설정할 수 있습니다.

alias jsonpp="python -c 'import sys, json; print json.dumps(json.load(sys.stdin), sort_keys=True, indent=2)'"

그런 다음 다음 방법 중 하나로 별칭을 사용합니다.

cat myfile.json | jsonpp
jsonpp < myfile.json

<답변7>

pprint 사용 : https://docs.python.org/3.6/library/pprint.html

import pprint
pprint.pprint(json)

print ()와 pprint.pprint () 비교

print(json)
{'feed': {'title': 'W3Schools Home Page', 'title_detail': {'type': 'text/plain', 'language': None, 'base': '', 'value': 'W3Schools Home Page'}, 'links': [{'rel': 'alternate', 'type': 'text/html', 'href': 'https://www.w3schools.com'}], 'link': 'https://www.w3schools.com', 'subtitle': 'Free web building tutorials', 'subtitle_detail': {'type': 'text/html', 'language': None, 'base': '', 'value': 'Free web building tutorials'}}, 'entries': [], 'bozo': 0, 'encoding': 'utf-8', 'version': 'rss20', 'namespaces': {}}

pprint.pprint(json)
{'bozo': 0,
 'encoding': 'utf-8',
 'entries': [],
 'feed': {'link': 'https://www.w3schools.com',
          'links': [{'href': 'https://www.w3schools.com',
                     'rel': 'alternate',
                     'type': 'text/html'}],
          'subtitle': 'Free web building tutorials',
          'subtitle_detail': {'base': '',
                              'language': None,
                              'type': 'text/html',
                              'value': 'Free web building tutorials'},
          'title': 'W3Schools Home Page',
          'title_detail': {'base': '',
                           'language': None,
                           'type': 'text/plain',
                           'value': 'W3Schools Home Page'}},
 'namespaces': {},
 'version': 'rss20'}

<답변8>

다음은 JSON이 컴퓨터에 로컬 파일로있을 필요없이 Python에서 멋진 방식으로 콘솔에 JSON을 인쇄하는 간단한 예제입니다.

import pprint
import json 
from urllib.request import urlopen # (Only used to get this example)

# Getting a JSON example for this example 
r = urlopen("https://mdn.github.io/fetch-examples/fetch-json/products.json")
text = r.read() 

# To print it
pprint.pprint(json.loads(text))

<답변9>

def saveJson(date,fileToSave):
    with open(fileToSave, 'w+') as fileToSave:
        json.dump(date, fileToSave, ensure_ascii=True, indent=4, sort_keys=True)

파일을 표시하거나 저장하는 데 사용됩니다.


<답변10>

pprintjson을 시도해 볼 수 있습니다.

$ pip3 install pprintjson

pprintjson CLI를 사용하여 파일에서 JSON을 깔끔하게 인쇄합니다.

$ pprintjson "./path/to/file.json"

pprintjson CLI를 사용하여 stdin에서 JSON을 예쁜 인쇄합니다.

$ echo '{ "a": 1, "b": "string", "c": true }' | pprintjson

pprintjson CLI를 사용하여 문자열에서 JSON을 깔끔하게 인쇄합니다.

$ pprintjson -c '{ "a": 1, "b": "string", "c": true }'

들여 쓰기가 1 인 문자열에서 JSON을 예쁘게 인쇄합니다.

$ pprintjson -c '{ "a": 1, "b": "string", "c": true }' -i 1

문자열에서 JSON을 예쁘게 인쇄하고 output.json 파일에 출력을 저장합니다.

$ pprintjson -c '{ "a": 1, "b": "string", "c": true }' -o ./output.json


<답변11>

오류를 피하기 위해 전에 json을 구문 분석하는 것이 더 낫다고 생각합니다.

def format_response(response):
    try:
        parsed = json.loads(response.text)
    except JSONDecodeError:
        return response.text
    return json.dumps(parsed, ensure_ascii=True, indent=4)

<답변12>

완벽하지는 않지만 제대로 작동합니다.

data = data.replace(',"',',\n"')

개선하고 들여 쓰기를 추가하는 등의 작업을 할 수 있지만 더 깨끗한 json을 읽을 수 있기를 원한다면 이것이 갈 길입니다.

반응형