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