You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将API获取的新JSON数据追加到文件而非覆盖更新?

问题分析与解决方案

你预期的JSON格式不符合JSON规范——JSON对象不允许存在重复键,即便手动写出这种结构,解析器也只会保留最后一组重复键的取值。正确的做法是将多条ISS位置记录存储在JSON数组中,合法结构示例如下:

[
    {
        "timestamp": 1690471995,
        "message": "success",
        "iss_position": {
            "latitude": "-40.3966",
            "longitude": "172.0519"
        }
    },
    {
        "timestamp": 1690472149,
        "message": "success",
        "iss_position": {
            "latitude": "-45.6057",
            "longitude": "-176.9845"
        }
    }
]

你的代码使用字典update()方法,本质是替换相同键的取值,而非追加新记录。以下是修正后的实现:

import requests
import json
import os

# 获取ISS实时数据
r = requests.get(url="http://api.open-notify.org/iss-now.json")
new_record = r.json()

file_path = "./35/test.json"

# 首次运行时创建空数组文件
if not os.path.exists(file_path):
    with open(file_path, "w") as f:
        json.dump([], f, indent=4)

# 读取现有数据并追加新记录
with open(file_path, "r") as f:
    records = json.load(f)
    records.append(new_record)

# 将更新后的数组写回文件
with open(file_path, "w") as f:
    json.dump(records, f, indent=4)

关键修改说明

  1. 直接复用接口返回的JSON数据,避免手动拼接字段的冗余操作
  2. 处理文件不存在的边界情况,初始化空数组保证首次运行正常
  3. 使用数组append()方法实现记录追加,替代字典update()的覆盖逻辑

内容的提问来源于stack exchange,提问作者useless experiments

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 20:57:36