How to get all API tokens from a JSON list
<p>So, basically I have a loop that retrieves all of the API tokens I need in order to run another get call.</p>

<p>Here is a segment of my code:</p>

<pre><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)
</code></pre>

<p>Here is an example of the json:</p>

<pre><code>{"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"}}
</code></pre>

<p>With my code I am getting an error on the first line.</p>

<blockquote>
  <p>typeerror string indices must be integers</p>
</blockquote>

<p>I just do not know how to only pull the API tokens.</p>

<p>data_2 :</p>

<pre><code>{'meta': {'httpStatus': '200 - OK', 'requestId': 'ewrfsdafasffds'}, 'result': {'apiToken': 'sdfdagfdfsgsd'}}
</code></pre>

<p>As per your comment</p>

<blockquote>
  <p>typeerror string indices must be integers</p>
</blockquote>

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

<pre><code>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)
</code></pre>

<p><strong>EDIT2</strong></p>

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

<pre><code>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)
</code></pre>

<p><strong>EDIT3</strong></p>

<p>Ok, so</p>

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

<p>therefore <code>data_2</code> is a dictionary.</p>

<pre><code>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)
</code></pre>

python json