如何使用 python 格式化 JSON 样式的文本?
How to format JSON style text using python?
我编写了一个将 KML 转换为 GeoJSON 的程序。但是,当我查看输出文件时,它们没有空格,很难阅读。
我尝试像这样使用 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
采用文件对象,而不是文件名。
with open("filename") as fh:
d = json.load(fh)
一旦你解析了它,你可以再次转储它,但格式更漂亮一些
with open("formatted-filename.json", "w") as fh:
json.dump(d, fh, indent=4)
我编写了一个将 KML 转换为 GeoJSON 的程序。但是,当我查看输出文件时,它们没有空格,很难阅读。
我尝试像这样使用 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
采用文件对象,而不是文件名。
with open("filename") as fh:
d = json.load(fh)
一旦你解析了它,你可以再次转储它,但格式更漂亮一些
with open("formatted-filename.json", "w") as fh:
json.dump(d, fh, indent=4)