【问题标题】:Formatting json file in Python在 Python 中格式化 json 文件
【发布时间】:2018-04-22 16:25:15
【问题描述】:
counter={"a":1,"b":2}
With open('egg.json' , 'w') as json_file:
   json.dump(counter, json_file)

所以当我查看我的 json 文件时,它会显示: {a:1 , b:2} 但我需要它是这样的:

[[a:1],[b:2]]

我已经尝试添加

json.dump(counter, json_file, separator (' [  ', ' ] ')

但是没有什么能解决问题... 有没有办法像格式化 CSV 文件一样格式化 json 文件? 我真的很想知道.....谢谢。

【问题讨论】:

  • 您为什么要这样做? dict 格式为 {} ...你知道xy-Problems
  • 如果你生成了无效的 json,你就会给消费者带来很大的困难——想想看。

标签: json python-3.x formatting


【解决方案1】:

[a:1], [b:2] 不是有效的 json,所以在这里使用 json 模块对您没有帮助。

如果出于某种原因您想要格式化字符串输出,您可以改为执行以下操作(不要调用文件 egg.json,因为它不是有效的 json!):

counter = {'a':1, 'b':2}
output = []
for k, v in sorted(counter.items()):
  output.append('[{}:{}]'.format(k, v))
with open('egg.txt', 'w') as txt_f:
    txt_f.write(', '.join(output))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-21
    • 2014-08-28
    • 2015-12-05
    • 1970-01-01
    • 2021-07-03
    • 1970-01-01
    相关资源
    最近更新 更多