Requesting and Parsing a JSON with Python
<p>I have this code below that I'm working on as part of an AI project. I'm looking to get tags that the user searches and return a url of a post with said tags.</p>

<pre><code>from meya import Component
import requests
import json

API_URL = "https://e621.net/post/index.json?limit=1&amp;tags=rating:s+order:random+{tag}"

class e621_call(Component):
"""Produces a e621 post based on the user's tags."""

def start(self):
    tag = self.properties.get('tag') or \
        self.db.flow.get('tag')

    response = requests.get(API_URL.format(tag=tag))

    img = response.json()['file_url']

    message = self.create_message(text=img)

    return self.respond(message=message, action="next")
</code></pre>

<p>Everything is fine up until I assign img to the <em>file_url</em> value, which brings up a</p>

<pre><code>TypeError: list indices must be integers, not str
</code></pre>

<p>For the record, I am using meya.ai for this, and the packages are not the issue</p>

<p>Your API returns a dictionary inside a list. Get inside the list first then you can do what you wish with the dictionary.</p>

<pre><code>response = requests.get(API_URL)
foo = json.loads(response.content)
file_url = foo[0].get('file_url')
</code></pre>

<p>If you plan on having multiple dictionaries returned inside the list, you can just loop through foo and find the multiple urls.</p>

<pre><code>for d in foo:
    print d.get('file_url')
</code></pre>

<p>Also, I prefer to not use .json() (As you may have noticed I didn't include it in my answer) because that way you can correctly check for the status_code first before proceeding. Otherwise if you get a 404 or a 500 for example, you will get errors.</p>

<pre><code>if response.status_code == 200:
    do stuff here
else:
    print "Something is wrong"
</code></pre>

python json parsing