编程语言
首页 > 编程语言> > 【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)

标签:indent,dump,show,python,jpg,json,格式化,data
来源: https://blog.csdn.net/u011622208/article/details/121197965