代码之家  ›  专栏  ›  技术社区  ›  Prithwiraj Samanta

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

  •  0
  • Prithwiraj Samanta  · 技术社区  · 4 年前

    我试图用一些数组对象动态创建下面的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()
    
    0 回复  |  直到 4 年前
        1
  •  0
  •   Blake    4 年前

    你可以试试这个:

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

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