无法从 python 漂亮地打印 json
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16318543/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can't pretty print json from python
提问by user1491250
Whenever I try to print out json from python, it ignores line breaks and prints the literal string "\n" instead of new line characters.
每当我尝试从 python 打印出 json 时,它都会忽略换行符并打印文字字符串“\n”而不是换行符。
I'm generating json using jinja2. Here's my code:
我正在使用 jinja2 生成 json。这是我的代码:
print json.dumps(template.render(**self.config['templates'][name]))
It prints out everything in the block below (literally - even the quotes and "\n" strings):
它打印出下面块中的所有内容(字面意思 - 甚至是引号和“\n”字符串):
"{\n \"AWSTemplateFormatVersion\" : \"2010-09-09\",\n \"Description\" : ...
(truncated)
(截断)
I get something like this whenever I try to dump anything but a dict. Even if I try json.loads() then dump it again I get garbage. It just strips out all line breaks.
每当我尝试转储除 dict 之外的任何内容时,我都会得到类似的信息。即使我尝试 json.loads() 然后再次转储它,我也会得到垃圾。它只是去除所有换行符。
What's going wrong?
怎么了?
采纳答案by felixbr
This is what I use for pretty-printing json-objects:
这是我用于漂亮打印 json 对象的内容:
def get_pretty_print(json_object):
return json.dumps(json_object, sort_keys=True, indent=4, separators=(',', ': '))
print get_pretty_print(my_json_obj)
json.dumps()also accepts parameters for encoding, if you need non-ascii support.
json.dumps()如果您需要非 ascii 支持,还接受编码参数。
回答by Tim Pietzcker
json.dumps()returns a JSON-encoded string. The JSON standard mandates that newlines are encoded as \\n, which is then printed as \n:
json.dumps()返回一个 JSON 编码的字符串。JSON 标准要求换行符编码为\\n,然后打印为\n:
>>> s="""hello
... there"""
>>> s
'hello\nthere'
>>> json.dumps(s)
'"hello\nthere"'
>>> print(json.dumps(s))
"hello\nthere"
There's not much you can do to change that if you want to keep a valid JSON string. If you want to print it, the correct way would be to print the JSON object, not its string representation:
如果你想保留一个有效的 JSON 字符串,你可以做很多事情来改变它。如果你想打印它,正确的方法是打印 JSON object,而不是它的字符串表示:
>>> print(s)
hello
there
>>> print(json.loads(json.dumps(s))) # pointless; just for demonstration...
hello
there
回答by zelusp
If your string is already JSON then pretty print it using
如果您的字符串已经是 JSON,那么使用
def pp_json(json_string):
# converts json to dict then back to string... ridiculous but not pointless
print(json.dumps(json.loads(json_string), sort_keys=True, indent=4))
return
pp_json(your_json_string)
回答by Eric des Courtis
The the problem is that your input to json.dumpsis a string. Try the following:
问题是您的输入json.dumps是string. 请尝试以下操作:
print type(template.render(**self.config['templates'][name]))
It you are doing this to indent etc... try the following:
如果您这样做是为了缩进等...请尝试以下操作:
print json.dumps(json.loads(template.render(**self.config['templates'][name])), sort_keys=True, indent=4)

