为什么我会收到“KeyError:‘data’”运行脚本时出错?

发布于 2025-01-10 05:10:55 字数 745 浏览 0 评论 0原文

我正在使用 Tableau Prep Builder 运行一个 Python 脚本,该脚本从名为 Supermetrics 的数据连接器提取 API。我正在密切关注此处。当我运行脚本时,我收到以下消息:

System error: Something went wrong when running the script. Verify that there are no errors in the script, then try again. KeyError : 'data'

这是脚本:

import requests
import pandas as pd
def get_data_to_flow(input):
    response = requests.get("[PLACEHOLDER FOR YOUR API LINK]")
    results = response.json()
    return pd.DataFrame(results['data'][1:], columns=results['data'][0])

脚本最初工作正常,但第二天运行后我开始看到此错误。我完全按照教程进行操作,并使用了有效的 API 链接。这个错误是什么意思以及如何修复它?

I am using Tableau Prep Builder to run a Python script that pulls in an API from a data connector called Supermetrics. I am following closely along with their tutorial seen here. When I run the script I get this message:

System error: Something went wrong when running the script. Verify that there are no errors in the script, then try again. KeyError : 'data'

This is the script:

import requests
import pandas as pd
def get_data_to_flow(input):
    response = requests.get("[PLACEHOLDER FOR YOUR API LINK]")
    results = response.json()
    return pd.DataFrame(results['data'][1:], columns=results['data'][0])

The script worked initally but after running it the next day I started to see this error. I have followed the tutorial perfectly and have used an API link that works. What does this error mean and how can I fix it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

一张白纸 2025-01-17 05:10:55

因为 results 是一个字典,不包含键 data。您没有检查您的 API 是否返回有效数据。

如果 API 返回错误,则对响应调用 raise_for_status() 以获取错误。

除此之外,也许没有错误,并且返回的数据的形状自上次使用以来发生了变化?

import requests
import pandas as pd

def get_data_to_flow(input):
    response = requests.get("[PLACEHOLDER FOR YOUR API LINK]")
    response.raise_for_status()
    results = response.json()
    data = results['data']
    return pd.DataFrame(data[1:], columns=data[0])

Because results, a dict, doesn't contain the key data. You aren't checking if your API returns valid data or not.

Call raise_for_status() on the response to get an error if the API returns an error.

Beyond that, maybe there isn't an error and shape of the data returned has changed since the last time you've used it?

import requests
import pandas as pd

def get_data_to_flow(input):
    response = requests.get("[PLACEHOLDER FOR YOUR API LINK]")
    response.raise_for_status()
    results = response.json()
    data = results['data']
    return pd.DataFrame(data[1:], columns=data[0])
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文