Javascript

【json】——python创建json文件格式化

本文主要是介绍【json】——python创建json文件格式化,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

python, json

在用json.dump写入json文件的时候加入indent参数就行
out_path = ‘./test.json’
json.dump(json_content, open(out_path, ‘w’), indent=2)

example

import json
jsonpath = './test.json'
jsonpath2 = './test2.json'
data = {
  "carDark": {
    "name": "CarDark",
    "image_files": [
      "0001.jpg",
      "0002.jpg",
      "0003.jpg",
      "0004.jpg",
      "0005.jpg",
    ],
    "init_rect": [
      73,
      126,
      29,
      23
    ],
    }
}
# one line show
data1 = json.dumps(data)
# multi lines show as dict format
data2 = json.dumps(data, indent=2) # indent 表示缩进
# write to json file , one line show
with open(jsonpath, 'w') as f:
  json.dump(data, f)
# write to json file , multi lines show as dict format
with open(jsonpath2, 'w') as f:
  json.dump(data, f, indent=2)
这篇关于【json】——python创建json文件格式化的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!