英文:
i want to add every new json data which i get from this api but it updates the files instead of appending it what to do
问题
我想将每次从这个API获取的新JSON数据添加到文件中,但它会更新文件而不是追加数据,该怎么办?
代码
import requests
import json
r = requests.get(url="http://api.open-notify.org/iss-now.json")
a = r.json()
latitude = a["iss_position"]["latitude"]
longitude = a["iss_position"]["longitude"]
timestamp = a["timestamp"]
new_data = {
"timestamp": timestamp,
"message": "success",
"iss_position": {
"latitude": latitude,
"longitude": longitude
}
}
with open("./35/test.json", mode="r") as data_file:
load = json.load(data_file)
load.update(new_data)
with open("./35/test.json", mode="w") as data_file:
json.dump(load, data_file, indent=4)
输出
我原本期望这段代码会将数据添加到我的test.json文件中,但实际上它并不是追加数据,而是不断更新旧数据。
英文:
I want to add every new json data which I get from this api but it updates the files instead of appending it what to do
Code
import requests
import json
r=requests.get(url="http://api.open-notify.org/iss-now.json")
a=r.json()
latitude=a["iss_position"]["latitude"]
longitude=a["iss_position"]["longitude"]
timestamp=a["timestamp"]
new_data={
"timestamp": timestamp,
"message": "success",
"iss_position": {
"latitude": latitude,
"longitude": longitude
}
}
with open("./35/test.json",mode="r") as data_file:
load=json.load(data_file)
load.update(new_data)
with open("./35/test.json",mode="w") as data_file:
json.dump(load,data_file,indent=4)
Output
I was expecting this code will do this
{
"timestamp": 1690471995,
"message": "success",
"iss_position": {
"latitude": "-40.3966",
"longitude": "172.0519"
}
"timestamp": 1690472149,
"message": "success",
"iss_position": {
"latitude": "-45.6057",
"longitude": "-176.9845"
}
}
to my test.json file but it does not append rather it just keeps on updating the old one
答案1
得分: 1
因为您正在使用相同的key
进行编写;dict
ionaries不允许有多个相同的key
。
一个解决方法是为每个数据条目使用唯一的key
,例如timestamp
s:
new_data = {
'timestamp_' + str(timestamp): {
"timestamp": timestamp,
"message": "success",
"iss_position": {
"latitude": latitude,
"longitude": longitude
}
}
}
这只需要增加一层嵌套;现在每个数据条目都与特定的timestamp
关联。
英文:
Because you're writing over the same key
s; dict
ionaries don't allow multiples of the same key
.
One work around would be to have unique key
s associated with each data entry, for example the timestamp
s:
new_data = {
'timestamp_ ' + str(timestamp): {
"timestamp": timestamp,
"message": "success",
"iss_position": {
"latitude": latitude,
"longitude": longitude
}
}
}
This just requires another level of nesting; each data entry is now associated with a specific timestamp
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论