如何使用Python在新括号开始之前使文本编辑器中的JSON输出转到下一行?

时间:2019-04-24 18:26:10

标签: python json text-editor

如何将json输出输出到文本编辑器中并进行组织,以便新括号的开头从下一行开始,以便看上去整洁?

with open(output, 'w') as json_file:
      rows = list(out)
      json.dump(rows, json_file) 

这是将我打印出json的代码的结尾,但并不整洁。

[{column1:value1,column2:value1},{column1:value2,column2:value2},{column1:value3,column2:value3},{column1:value4,column2:value4}]

我已经尝试过了。但是我收到一条错误消息。

with open(output, 'w') as json_file:
       rows = list(out)
       json.dump(rows, json_file) + ',' + '\n'

我希望结果看起来像

[{column1:value1,column2:value1},
{column1:value2,column2:value2}, 
{column1:value3,column2:value3},
{column1:value4,column2:value4}]

1 个答案:

答案 0 :(得分:0)

虽然json module允许选择缩进,但我不知道如何生成自定义布局。
因此,我最好的解决方案是:

import json

path = "/path/to/json"
d = [
    {"column1": "value1", "column2": "value1"},
    {"column1": "value2", "column2": "value2"}, 
    {"column1": "value3", "column2": "value3"},
    {"column1": "value4", "column2": "value4"}
]


lines = "["
for x in d[:-1]:
    lines += json.dumps(x) + ",\n"
lines += json.dumps(d[-1]) + "]"
with open(path, "w") as f:
    f.write(lines)