不能从python中打印json

use*_*250 13 python json

每当我尝试从python打印出json时,它会忽略换行符并打印文字字符串"\n"而不是换行符.

我正在使用jinja2生成json.这是我的代码:

print json.dumps(template.render(**self.config['templates'][name]))
Run Code Online (Sandbox Code Playgroud)

它打印出下面块中的所有内容(字面意思 - 甚至是引号和"\n"字符串):

"{\n    \"AWSTemplateFormatVersion\" : \"2010-09-09\",\n    \"Description\" : ... 
Run Code Online (Sandbox Code Playgroud)

(截短的)

每当我试图抛弃任何东西而不是一个字典时,我会得到这样的东西.即使我尝试json.loads()然后再转储它我得到垃圾.它只是删除所有换行符.

出了什么问题?

fel*_*xbr 17

这是我用于漂亮打印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)
Run Code Online (Sandbox Code Playgroud)

json.dumps() 如果您需要非ascii支持,也接受编码参数.

  • 不,这不起作用.它没有解决'print'实际打印"\n"而不是新行字符这一事实的问题. (2认同)
  • 如果使用JSON-_object_(或者更确切地说是python中的dict)作为`json.dumps()`的输入,它确实有效.如果已经有一个表示为字符串的JSON对象,则不再需要`json.dumps()`. (2认同)

Tim*_*ker 7

json.dumps()返回JSON编码的字符串.JSON标准要求将换行符编码为\\n,然后将其打印为\n:

>>> s="""hello
... there"""
>>> s
'hello\nthere'
>>> json.dumps(s)
'"hello\\nthere"'
>>> print(json.dumps(s))
"hello\nthere"
Run Code Online (Sandbox Code Playgroud)

如果要保留有效的JSON字符串,则无法更改它.如果要打印它,正确的方法是打印JSON 对象,而不是它的字符串表示:

>>> print(s)
hello
there
>>> print(json.loads(json.dumps(s)))  # pointless; just for demonstration...
hello
there
Run Code Online (Sandbox Code Playgroud)