【问题标题】:How do I print a .json file in python [duplicate]如何在 python 中打印 .json 文件 [重复]
【发布时间】:2022-01-08 05:45:42
【问题描述】:

我想知道是否有人知道如何在 python 中使用与从 JavaScript 运行它相同的格式打印 .json 文件。我将它用于 api 使用,输出是 .json 但是当我打印它时,我得到了这个: link to image

但是 api 文档有这个: another image

(图片显示了它的不同部分)

【问题讨论】:

标签: javascript python json


【解决方案1】:

我猜你的意思是如何打印格式化的 json,如果是这样,你可以这样做

import json
with open('yourfile.json', 'r') as handle:
    parsed = json.load(handle)
print(json.dumps(parsed, indent=4, sort_keys=True))

如果你想像 Javascript 那样做,有办法

var str = JSON.stringify(YourJsonObject, null, 4);

或者其他方式

import json 
     
# Opening JSON file 
f = open('yourjsonfile.json',) 
     
# returns JSON object as  
# a dictionary 
data = json.load(f) 
     
print(json.dumps(data, indent = 4)
     
# Closing file 
f.close() 

还有

import json

print json.dumps(jsonstring, indent=4)

【讨论】:

    【解决方案2】:

    这应该可以解决问题:

    import json
    print(json.dumps(my_input, sort_keys=True, indent=4))
    

    https://docs.python.org/3/library/json.html

    【讨论】:

      猜你喜欢
      • 2015-04-06
      • 1970-01-01
      • 2016-07-20
      • 2013-08-19
      • 2021-03-14
      • 1970-01-01
      • 2022-01-21
      • 2020-05-31
      • 2019-08-06
      相关资源
      最近更新 更多