繁体   English   中英

如何使用python动态创建json文件(带有数组类型对象)

[英]How to create json file ( with array type object) dynamically using python

我正在尝试使用一些数组对象动态创建以下 json 文件:

{
  "timestamp": "Timestamp",
  "year":"2020"
  "actions": {
    "copy": {
      "id": [1,2]
    }
  }
}

其中只有 id 会动态生成。 我尝试创建以下代码,但遇到了一些问题。 任何建议请:

import json
import os


def write_json():
    # create a dictionary
    data = {
        "timestamp": "Timestamp",
        "year":"2020",
        "actions": {
          "copy":    {
            "id": []
    }
  }
}
    #create a list
    data_holder = data["name"]
    # just a counter
    counter = 0
    while counter < 2:
        data_holder.append({counter})
        counter += 1
    #write the file
    path = os.getenv("HOME")
    file_path=path+'/'+'data.json'
    with open(file_path, 'w') as outfile:
        print("writing file to: ",file_path)
        json.dump(data, outfile)
    outfile.close()
    print("done")

write_json()

你可以试试这个:

def write_json():
    # create a dictionary
    data = {
        "timestamp": "Timestamp",
        "year": "2020",
        "actions": {
            "copy": {
                "id": []
            }
        }
    }

# additional code here...

with open("FILE PATH HERE", 'w') as outfile:
    x = json.dumps(data)
    outfile.write(x)

outfile.close()

if __name__ == "__main__":
    write_json()

使用有效的文件路径对我有用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM