【问题标题】:How to create json file ( with array type object) dynamically using python如何使用python动态创建json文件(具有数组类型对象)
【发布时间】:2020-10-23 02:33:26
【问题描述】:

我正在尝试使用一些数组对象动态创建下面的 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()

【问题讨论】:

  • 我尝试创建以下代码,但遇到了一些问题我们应该猜出问题是什么吗?

标签: python arrays json


【解决方案1】:

你可以试试这个:

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()

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

【讨论】:

    猜你喜欢
    • 2011-09-29
    • 1970-01-01
    • 2011-04-12
    • 2023-03-25
    • 2014-12-13
    • 1970-01-01
    • 2013-04-25
    • 2022-01-03
    • 1970-01-01
    相关资源
    最近更新 更多