问题:如何打印JSON文件?

我有一个JSON文件,我想对其进行漂亮打印-在python中执行此操作的最简单方法是什么?我知道PrettyPrint带有一个“对象”,我认为它可以是一个文件,但是我不知道如何传递文件-仅使用文件名是行不通的。

I have a JSON file that is a mess that I want to prettyprint– what’s the easiest way to do this in python? I know PrettyPrint takes an “object”, which I think can be a file, but I don’t know how to pass a file in– just using the filename doesn’t work.


回答 0

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)

The json module already implements some basic pretty printing with the indent parameter:

>>> 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
        ]
    }
]

To parse a file, use json.load():

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

回答 1

您可以在命令行上执行此操作:

python3 -m json.tool some.json

(正如问题注释中已经提到的,感谢@Kai Petzke的python3建议)。

实际上,就命令行上的json处理而言,python不是我最喜欢的工具。简单的漂亮打印是可以的,但是如果您要操作json,它可能会变得过于复杂。您很快就需要编写一个单独的脚本文件,最终可能得到其键为u“ some-key”(python unicode)的地图,这会使选择字段更加困难,并且实际上并没有朝着漂亮的方向发展。 -印刷。

您也可以使用jq

jq . some.json

并获得颜色作为奖励(并且更容易扩展)。

附录:关于使用jq一方面处理大型JSON文件,另一方面使用非常大的jq程序的注释有些混乱。对于漂亮地打印由单个大型JSON实体组成的文件,实际的限制是RAM。对于漂亮地打印由单个真实数据数组组成的2GB文件,漂亮打印所需的“最大驻留集大小”为5GB(无论使用jq 1.5还是1.6)。还要注意,jq可以在python之后使用pip install jq

You can do this on the command line:

python3 -m json.tool some.json

(as already mentioned in the commentaries to the question, thanks to @Kai Petzke for the python3 suggestion).

Actually python is not my favourite tool as far as json processing on the command line is concerned. For simple pretty printing is ok, but if you want to manipulate the json it can become overcomplicated. You’d soon need to write a separate script-file, you could end up with maps whose keys are u”some-key” (python unicode), which makes selecting fields more difficult and doesn’t really go in the direction of pretty-printing.

You can also use jq:

jq . some.json

and you get colors as a bonus (and way easier extendability).

Addendum: There is some confusion in the comments about using jq to process large JSON files on the one hand, and having a very large jq program on the other. For pretty-printing a file consisting of a single large JSON entity, the practical limitation is RAM. For pretty-printing a 2GB file consisting of a single array of real-world data, the “maximum resident set size” required for pretty-printing was 5GB (whether using jq 1.5 or 1.6). Note also that jq can be used from within python after pip install jq.


回答 2

您可以使用内置的modul pprint(https://docs.python.org/3.6/library/pprint.html)

如何读取带有json数据的文件并打印出来。

import json
import pprint

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

pprint.pprint(json_data)

You could use the built-in modul pprint (https://docs.python.org/3.6/library/pprint.html).

How you can read the file with json data and print it out.

import json
import pprint

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

pprint.pprint(json_data)

回答 3

Pygmentize + Python json.tool =带有语法突出显示的漂亮打印

Pygmentize是杀手级工具。看到这个。

我结合python json.tool与pygmentize

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

有关pygmentize安装说明,请参见上面的链接。

下图是一个演示:

演示

Pygmentize + Python json.tool = Pretty Print with Syntax Highlighting

Pygmentize is a killer tool. See this.

I combine python json.tool with pygmentize

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

See the link above for pygmentize installation instruction.

A demo of this is in the image below:

demo


回答 4

使用此功能,不出汗不必记住,如果你的JSON是一种strdict再次-这个漂亮的打印只要看看:

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)

Use this function and don’t sweat having to remember if your JSON is a str or dict again – just look at the pretty print:

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)

回答 5

我曾经写过一个prettyjson()函数来产生漂亮的输出。您可以从此仓库中获取实现。

此功能的主要功能是尝试将dict和list项目保持在一行中,直到maxlinelength达到确定的水平为止。这样会产生更少的JSON行,输出看起来更紧凑且更易于阅读。

您可以产生这种输出,例如:

{
  "grid": {"port": "COM5"},
  "policy": {
    "movingaverage": 5,
    "hysteresis": 5,
    "fan1": {
      "name": "CPU",
      "signal": "cpu",
      "mode": "auto",
      "speed": 100,
      "curve": [[0, 75], [50, 75], [75, 100]]
    }
}

UPD 19年12月:我将代码放入单独的存储库中,更正了一些错误,并进行了其他一些调整。

I once wrote a prettyjson() function to produce nice-looking output. You can grab the implementation from this repo.

The main feature of this function is it tries to keep dict and list items in one line until a certain maxlinelength is reached. This produces fewer lines of JSON, the output looks more compact and easier to read.

You can produce this kind of output for instance:

{
  "grid": {"port": "COM5"},
  "policy": {
    "movingaverage": 5,
    "hysteresis": 5,
    "fan1": {
      "name": "CPU",
      "signal": "cpu",
      "mode": "auto",
      "speed": 100,
      "curve": [[0, 75], [50, 75], [75, 100]]
    }
}

UPD Dec’19: I placed the code into a separate repo, corrected a few bugs and made a few other tweaks.


回答 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

To be able to pretty print from the command line and be able to have control over the indentation etc. you can set up an alias similar to this:

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

And then use the alias in one of these ways:

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'}

Use pprint: https://docs.python.org/3.6/library/pprint.html

import pprint
pprint.pprint(json)

print() compared to 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

这是一个简单的示例,可以在Python中以一种不错的方式将JSON打印到控制台,而无需将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))

Here’s a simple example of pretty printing JSON to the console in a nice way in Python, without requiring the JSON to be on your computer as a local file:

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)

它可以显示或保存到文件中。

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

It works to display or save it to a file.


回答 10

我认为最好先解析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)

I think that’s better to parse the json before, to avoid errors:

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

回答 11

您可以尝试pprintjson


安装

$ pip3 install pprintjson

用法

使用pprintjson CLI从文件漂亮地打印JSON。

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

使用pprintjson CLI从标准输入漂亮地打印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

输出量

在此处输入图片说明

You could try pprintjson.


Installation

$ pip3 install pprintjson

Usage

Pretty print JSON from a file using the pprintjson CLI.

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

Pretty print JSON from a stdin using the pprintjson CLI.

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

Pretty print JSON from a string using the pprintjson CLI.

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

Pretty print JSON from a string with an indent of 1.

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

Pretty print JSON from a string and save output to a file output.json.

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

Output

enter image description here


回答 12

它远非完美,但可以做到。

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

您可以对其进行改进,添加缩进等,但是如果您只想能够阅读更简洁的json,则可以采用这种方法。

It’s far from perfect, but it does the job.

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

you can improve it, add indenting and so on, but if you just want to be able to read a cleaner json, this is the way to go.


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。