【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)
上一篇:简单的PHP文件上传


下一篇:JavaScript项目实战 轮播图(手动切图)