gpt4 book ai didi

python - 如何从 html 和/或 python3 将数据添加/附加到 js 文件

转载 作者:太空宇宙 更新时间:2023-11-03 16:55:43 25 4
gpt4 key购买 nike

我想通过 python3 将数据添加到我的 data.js 文件中。有人有什么想法吗? data.js 文件如下所示:

{
"data":[
{"Name": "Bob", "Age": "21"},
{"Name": "Monty", "Age": "15"}
]
}

到目前为止,在 python 中我有这个:

import json
name = input("Name: ")
age = input("Age: ")
data = {
"Name": name,
"Age": age,
}

with open("data.js", "w") as file:
json.dump([data], f)

但是保存为[{"Name": "Bob", "Age": "23"}]

有人有什么建议吗?

最佳答案

您必须从头开始构建整个内容。

像这样:

import json
name = input("Name: ")
age = input("Age: ")
content = {'data': []} #This will be the final content of your js file

person1 = {"name": name, "Age": age} #Build objs for each person ...
content['data'].append(person1) # .. and append it to your 'data'

with open("data.js", "w") as file:
json.dump(content, f)

关于python - 如何从 html 和/或 python3 将数据添加/附加到 js 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35435115/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com