JSON文件格式清晰易读

时间:2019-06-12 17:46:11

标签: python json dictionary

我有一个.json文件,当前在txt编辑器中看起来是这样

{"a": [1,2,3], "b":[2,3], "c":[1,3,5]}

基本上,目前它拥有一本字典。我想知道是否有一种方法可以使用Python通过向每个键添加换行符来“美化” .json文件。 使用json缩进会导致:

{
   "a": [
          1,2,3
        ],
   "b":[
          2,3
       ],
   "c":[
          1,3,5
       ]
}

所以现在我要删除换行符和表格:

{
   "a": [1,2,3],
   "b":[2,3],
   "c":[1,3,5]
}

2 个答案:

答案 0 :(得分:0)

不太优雅,但是您可以使用字符串替换来格式化json,例如:

with open('foo.json', 'r') as handle:
    parsed = json.load(handle)

string_json = json.dumps(parsed, indent=0, sort_keys=True)
string_replaced = string_json.replace("\n", "").replace("{", "{\n").replace("],", "],\n").replace("}", "\n}")

这将提供您想要的输出,但是不确定它的可扩展性,因为它使用简单的字符串匹配

答案 1 :(得分:0)

对于与Python脚本位于同一目录中的data.json文件

{"a": [1,2,3], "b":[2,3], "c":[1,3,5]}

您可以读取原始JSON,然后使用“美化”版本覆盖原始文件。

import json
with open('data.json', 'r') as f:
    data = json.load(f)
with open('data.json', 'w') as f:
    json.dump(data, f, indent=2, sort_keys=True)

新的data.json

{
  "a": [
    1, 
    2, 
    3
  ], 
  "b": [
    2, 
    3
  ], 
  "c": [
    1, 
    3, 
    5
  ]
}