如何相印JSON文件?

时间:2012-10-17 21:38:43

标签: python json pretty-print

我有一个JSON文件是一个混乱,我想漂亮 - 在python中最简单的方法是什么?我知道PrettyPrint带有一个“对象”,我认为它可以是一个文件,但我不知道如何传入文件 - 只是使用文件名不起作用。

14 个答案:

答案 0 :(得分:1257)

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)

答案 1 :(得分:254)

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

python3 -m json.tool < some.json

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

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

我使用jq。以上可以通过以下方式完成:

jq '' < some.json

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

答案 2 :(得分:37)

您可以使用内置模块pprint

如何使用json数据读取文件并将其打印出来。

android {

 // some stuff
 packagingOptions {
        pickFirst 'lib/armeabi-v7a/libobjectbox.so'
        pickFirst 'lib/arm64-v8a/libobjectbox.so'
        pickFirst 'lib/x86_64/libobjectbox.so'
        pickFirst 'lib/x86/libobjectbox.so'
    }
}

答案 3 :(得分:32)

使用此功能,不必再记住您的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)

答案 4 :(得分:9)

为了能够从命令行进行漂亮打印并能够控制缩进等,您可以设置类似于此的别名:

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

答案 5 :(得分:4)

这是一个简单的例子,可以在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))

答案 6 :(得分:3)

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

答案 7 :(得分:2)

{
  "name": "translate",
  // Use lazy. You don't want to install unless they use the translation
  "installMode": "lazy", 
  // Use prefetch because you want it to update every time the app updates
  "updateMode": "prefetch",
  "resources": {
    "files": "/assets/i18n/*.json"
  }
}

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

答案 8 :(得分:1)

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

答案 9 :(得分:1)

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

此功能的主要功能是尝试将字典和项目保持在一行中,直到达到特定的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]]
    }
}

答案 10 :(得分:1)

您可以尝试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

输出

enter image description here

答案 11 :(得分:0)

我对转储json文件的内容进行记录有类似的要求,这是快速简便的事情:

print(json.dumps(json.load(open(os.path.join('<myPath>', '<myjson>'), "r")), indent = 4 ))

如果您经常使用它,则将其放在函数中:

def pp_json_file(path, file):
    print(json.dumps(json.load(open(os.path.join(path, file), "r")), indent = 4))

答案 12 :(得分:-1)

希望这对其他人有所帮助。

如果出现某些内容不是 json 可序列化的错误,则上述答案将不起作用。如果您只想保存它以便人类可读,那么您需要对字典的所有非字典元素递归调用字符串。如果您想稍后加载它,请将其另存为泡菜文件,然后加载它(例如 torch.save(obj, f) 工作正常)。

这对我有用:

#%%

def _to_json_dict_with_strings(dictionary):
    """
    Convert dict to dict with leafs only being strings. So it recursively makes keys to strings
    if they are not dictionaries.

    Use case:
        - saving dictionary of tensors (convert the tensors to strins!)
        - saving arguments from script (e.g. argparse) for it to be pretty

    e.g.

    """
    if type(dictionary) != dict:
        return str(dictionary)
    d = {k: _to_json_dict_with_strings(v) for k, v in dictionary.items()}
    return d

def to_json(dic):
    import types
    import argparse

    if type(dic) is dict:
        dic = dict(dic)
    else:
        dic = dic.__dict__
    return _to_json_dict_with_strings(dic)

def save_to_json_pretty(dic, path, mode='w', indent=4, sort_keys=True):
    import json

    with open(path, mode) as f:
        json.dump(to_json(dic), f, indent=indent, sort_keys=sort_keys)

def my_pprint(dic):
    """

    @param dic:
    @return:

    Note: this is not the same as pprint.
    """
    import json

    # make all keys strings recursively with their naitve str function
    dic = to_json(dic)
    # pretty print
    pretty_dic = json.dumps(dic, indent=4, sort_keys=True)
    print(pretty_dic)
    # print(json.dumps(dic, indent=4, sort_keys=True))
    # return pretty_dic

import torch
# import json  # results in non serializabe errors for torch.Tensors
from pprint import pprint

dic = {'x': torch.randn(1, 3), 'rec': {'y': torch.randn(1, 3)}}

my_pprint(dic)
pprint(dic)

输出:

{
    "rec": {
        "y": "tensor([[-0.3137,  0.3138,  1.2894]])"
    },
    "x": "tensor([[-1.5909,  0.0516, -1.5445]])"
}
{'rec': {'y': tensor([[-0.3137,  0.3138,  1.2894]])},
 'x': tensor([[-1.5909,  0.0516, -1.5445]])}

我不知道为什么返回字符串然后打印它不起作用,但似乎您必须将转储直接放在打印语句中。请注意 pprint,因为它已被建议也已经有效。请注意,并非所有对象都可以使用 dict(dic) 转换为 dict,这就是为什么我的某些代码会检查此条件的原因。

上下文:

我想保存 pytorch 字符串,但我一直收到错误:

TypeError: tensor is not JSON serializable

所以我对上面的代码进行了编码。请注意,是的,在 pytorch 中您使用 torch.save 但泡菜文件不可读。查看此相关帖子:https://discuss.pytorch.org/t/typeerror-tensor-is-not-json-serializable/36065/3


PPrint 也有缩进参数,但我不喜欢它的外观:

    pprint(stats, indent=4, sort_dicts=True)

输出:

{   'cca': {   'all': {'avg': tensor(0.5132), 'std': tensor(0.1532)},
               'avg': tensor([0.5993, 0.5571, 0.4910, 0.4053]),
               'rep': {'avg': tensor(0.5491), 'std': tensor(0.0743)},
               'std': tensor([0.0316, 0.0368, 0.0910, 0.2490])},
    'cka': {   'all': {'avg': tensor(0.7885), 'std': tensor(0.3449)},
               'avg': tensor([1.0000, 0.9840, 0.9442, 0.2260]),
               'rep': {'avg': tensor(0.9761), 'std': tensor(0.0468)},
               'std': tensor([5.9043e-07, 2.9688e-02, 6.3634e-02, 2.1686e-01])},
    'cosine': {   'all': {'avg': tensor(0.5931), 'std': tensor(0.7158)},
                  'avg': tensor([ 0.9825,  0.9001,  0.7909, -0.3012]),
                  'rep': {'avg': tensor(0.8912), 'std': tensor(0.1571)},
                  'std': tensor([0.0371, 0.1232, 0.1976, 0.9536])},
    'nes': {   'all': {'avg': tensor(0.6771), 'std': tensor(0.2891)},
               'avg': tensor([0.9326, 0.8038, 0.6852, 0.2867]),
               'rep': {'avg': tensor(0.8072), 'std': tensor(0.1596)},
               'std': tensor([0.0695, 0.1266, 0.1578, 0.2339])},
    'nes_output': {   'all': {'avg': None, 'std': None},
                      'avg': tensor(0.2975),
                      'rep': {'avg': None, 'std': None},
                      'std': tensor(0.0945)},
    'query_loss': {   'all': {'avg': None, 'std': None},
                      'avg': tensor(12.3746),
                      'rep': {'avg': None, 'std': None},
                      'std': tensor(13.7910)}}

比较:

{
    "cca": {
        "all": {
            "avg": "tensor(0.5144)",
            "std": "tensor(0.1553)"
        },
        "avg": "tensor([0.6023, 0.5612, 0.4874, 0.4066])",
        "rep": {
            "avg": "tensor(0.5503)",
            "std": "tensor(0.0796)"
        },
        "std": "tensor([0.0285, 0.0367, 0.1004, 0.2493])"
    },
    "cka": {
        "all": {
            "avg": "tensor(0.7888)",
            "std": "tensor(0.3444)"
        },
        "avg": "tensor([1.0000, 0.9840, 0.9439, 0.2271])",
        "rep": {
            "avg": "tensor(0.9760)",
            "std": "tensor(0.0468)"
        },
        "std": "tensor([5.7627e-07, 2.9689e-02, 6.3541e-02, 2.1684e-01])"
    },
    "cosine": {
        "all": {
            "avg": "tensor(0.5945)",
            "std": "tensor(0.7146)"
        },
        "avg": "tensor([ 0.9825,  0.9001,  0.7907, -0.2953])",
        "rep": {
            "avg": "tensor(0.8911)",
            "std": "tensor(0.1571)"
        },
        "std": "tensor([0.0371, 0.1231, 0.1975, 0.9554])"
    },
    "nes": {
        "all": {
            "avg": "tensor(0.6773)",
            "std": "tensor(0.2886)"
        },
        "avg": "tensor([0.9326, 0.8037, 0.6849, 0.2881])",
        "rep": {
            "avg": "tensor(0.8070)",
            "std": "tensor(0.1595)"
        },
        "std": "tensor([0.0695, 0.1265, 0.1576, 0.2341])"
    },
    "nes_output": {
        "all": {
            "avg": "None",
            "std": "None"
        },
        "avg": "tensor(0.2976)",
        "rep": {
            "avg": "None",
            "std": "None"
        },
        "std": "tensor(0.0945)"
    },
    "query_loss": {
        "all": {
            "avg": "None",
            "std": "None"
        },
        "avg": "tensor(12.3616)",
        "rep": {
            "avg": "None",
            "std": "None"
        },
        "std": "tensor(13.7976)"
    }
}

答案 13 :(得分:-6)

它远非完美,但可以完成。

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

您可以对其进行改进,添加缩进等,但是如果您只想读取更清晰的json,则可以采用这种方法。

相关问题