j doe j doe - 2 months ago 7
JSON Question

How to get all API tokens from a JSON list

So, basically I have a loop that retrieves all of the API tokens I need in order to run another get call.

Here is a segment of my code:

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)


Here is an example of the 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"}}


With my code I am getting an error on the first line.


typeerror string indices must be integers


I just do not know how to only pull the API tokens.

data_2 :

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

Answer

As per your comment

typeerror string indices must be integers

try updating your list comprehension (assuming that data_2 is a list of dicts and not a JSON string). It looks like you are iterating over the token characters.

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)

EDIT2

So data_2 may be a JSON string, not an dictionary (based on comments). In that case you can try the following:

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)

EDIT3

Ok, so

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

therefore data_2 is a dictionary.

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)