如何从JSON列表中获取所有API令牌

2024-05-16 00:48:04 发布

您现在位置:Python中文网/ 问答频道 /正文

所以,基本上我有一个循环,它检索我运行另一个get调用所需的所有API令牌。你知道吗

下面是我的一段代码:

tokens = [result['apiToken'] for result in data_2['result']['apiToken']]
for i in tokens:
    url = "https://swag.com"
    headers = {
    'x-api-token': i
    }
    response = requests.get(url, headers=headers)
    data = json.loads(response.text)

以下是json的一个示例:

{"result":{"apiToken":"sdfagdsfgdfagfdagda"},"meta":
{"httpStatus":"200 - OK","requestId":"12343-232-424332428-432-
4234555","notice":"Request proxied. For faster response times, use this 
host instead: swag.com"}}

我的代码在第一行出现了一个错误。你知道吗

typeerror string indices must be integers

我只是不知道如何只拉API令牌。你知道吗

数据表2:

{'meta': {'httpStatus': '200 - OK', 'requestId': 'ewrfsdafasffds'}, 'result': {'apiToken': 'sdfdagfdfsgsd'}}

Tags: 代码incomapijsonurlfordata
1条回答
网友
1楼 · 发布于 2024-05-16 00:48:04

根据你的意见

typeerror string indices must be integers

尝试更新列表理解(假设data_2是dict列表而不是JSON字符串)。看起来您正在对标记字符进行迭代。你知道吗

tokens = [result['apiToken'] for result in data_2['result']]
for i in tokens:
    url = "https://swag.com"
    headers = {
    'x-api-token': i
    }
    response = requests.get(url, headers=headers)
    data = json.loads(response.text)

编辑2

所以data_2可能是JSON字符串,而不是字典(基于注释)。在这种情况下,您可以尝试以下操作:

import json

tokens = [result['apiToken'] for result in json.loads(data_2)]
for i in tokens:
    url = "https://swag.com"
    headers = {
    'x-api-token': i
    }
    response = requests.get(url, headers=headers)
    data = json.loads(response.text)

编辑3

好吧,那么

Earlier in the code I got a response named response.text and I did data_2 = json.loads(resopnse.text)

因此data_2是一本字典。你知道吗

tokens = [data_2['result']['apiToken']]
for i in tokens:
    url = "https://swag.com"
    headers = {
    'x-api-token': i
    }
    response = requests.get(url, headers=headers)
    data = json.loads(response.text)

相关问题 更多 >