简体   繁体   English

如何使用python格式化JSON样式文本?

[英]How to format JSON style text using python?

I wrote a program to convert KML to GeoJSON.我编写了一个程序将 KML 转换为 GeoJSON。 But, when I look at the output files, they are written without whitespace, making them very hard to read.但是,当我查看输出文件时,它们没有空格,因此很难阅读。

I tried to use the json module like so: file = json.load("<filename>") But it returned the following:我尝试像这样使用 json 模块: file = json.load("<filename>")但它返回了以下内容:

File "/usr/lib/python3.6/json/__init__.py", line 296, in load
    return loads(fp.read())
AttributeError: 'str' has no attribute 'read'

load takes a file object, not a file name. load需要一个文件对象,而不是一个文件名。

with open("filename") as fh:
    d = json.load(fh)

Once you've parsed it, you can dump it again, but formatted a bit more nicely一旦你解析了它,你可以再次转储它,但格式化得更好一点

with open("formatted-filename.json", "w") as fh:
    json.dump(d, fh, indent=4)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM