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

如何在Python中提取API返回JSON指定字段并写入Google Sheet?

解决方案

一、提取"item count"字段

首先把API返回的JSON数据解析为Python字典,再根据字段的层级关系提取目标值。如果直接搜索失败,大概率是字段嵌套在深层结构里,建议先格式化打印数据结构来定位。

1. 基础提取代码

import requests
from pprint import pprint  # 格式化打印JSON结构,方便定位字段位置

headers = {
    'Accept': 'application/json',
    'x-api-key': 'apikey'
}

response = requests.get('https://app.myapp.com/api/v3/agents/100', headers=headers)
data = response.json()

# 打印格式化后的JSON结构,快速找到"item count"的层级路径
pprint(data)

# 根据实际结构提取字段,两种常见情况:
# 情况1:字段是顶层直接键
item_count = data.get("item count")
# 情况2:字段嵌套在子字典中(示例路径,需根据实际结构调整)
# item_count = data.get("agents", {}).get("stats", {}).get("item count")

if item_count is not None:
    print(f"提取到的item count值:{item_count}")
else:
    print("未找到'item count'字段,请检查JSON结构")
  • 用get()方法代替直接索引[],可避免字段不存在时抛出KeyError,还能设置默认值(比如data.get("item count", 0))。
  • 运行后通过pprint的输出,能清晰看到"item count"所在的层级路径。

二、写入Google Sheet

使用gspread库可以快速实现Python与Google Sheet的交互,步骤如下:

1. 安装依赖

pip install gspread oauth2client

2. 准备Google云服务账号

  • 登录Google Cloud控制台,创建新项目。
  • 在项目中启用Google Sheets API。
  • 创建服务账号,下载对应的JSON密钥文件(保存为service_account.json,放在代码同目录)。
  • 打开目标Google Sheet,点击右上角「分享」,把服务账号的邮箱(密钥文件的client_email字段)添加为编辑者。

3. 完整写入代码

将字段提取和写入逻辑结合:

import requests
import gspread
from oauth2client.service_account import ServiceAccountCredentials
from pprint import pprint

# 1. 调用API提取item count
headers = {
    'Accept': 'application/json',
    'x-api-key': 'apikey'
}

response = requests.get('https://app.myapp.com/api/v3/agents/100', headers=headers)
data = response.json()

# 根据实际层级调整提取路径
item_count = data.get("item count")
if item_count is None:
    print("未找到目标字段,终止写入")
    exit()

# 2. 连接Google Sheet并写入数据
# 定义权限范围
scope = ['https://www.googleapis.com/auth/spreadsheets',
         'https://www.googleapis.com/auth/drive']

# 加载密钥文件完成认证
creds = ServiceAccountCredentials.from_json_keyfile_name('service_account.json', scope)
client = gspread.authorize(creds)

# 打开目标表格(可用表格名称或ID)
sheet = client.open("你的表格名称").sheet1  # sheet1代表第一个工作表

# 写入数据:追加到第一列末尾
sheet.append_row([item_count])
print(f"成功写入数据:{item_count}")

额外说明

  • 若要写入指定单元格,可使用sheet.update_cell(row, col, value),比如sheet.update_cell(1, 1, item_count)表示写入A1单元格。
  • 确保服务账号拥有目标表格的编辑权限,否则会抛出权限错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 22:55:19