Traversing json array in python
<p>I'm using urllib.request.urlopen to get a JSON response that looks like this:</p>

<pre><code>{
"batchcomplete": "",
"query": {
    "pages": {
        "76972": {
            "pageid": 76972,
            "ns": 0,
            "title": "Title",
            "thumbnail": {
                "original": "https://linktofile.com"
            }
        }
    }
}
</code></pre>

<p>The relevant code to get the response:</p>

<pre><code>response = urllib.request.urlopen("https://example.com?title="+object.title)
data = response.read()
encoding = response.info().get_content_charset('utf-8')
json_object = json.loads(data.decode(encoding))
</code></pre>

<p>I'm trying to retrieve the value of "original", but I'm having a hard time getting there.
I can do <code>print(json_object['query']['pages']</code> but once I do <code>print(json_object['query']['pages'][0]</code> I run into a KeyError: 0.</p>

<p>How would I be able to, with python retrieve the value of <code>original</code>?</p>

<p>Do this instead:</p>

<pre><code>my_content = json_object['query']['pages']['76972']['thumbnail']['original']
</code></pre>

<p>The reason is, you need to mention <code>index</code> as <code>[0]</code> only when you have list as the object. But in your case, every item is of <code>dict</code> type. You need to specify <code>key</code> instead of <code>index</code></p>

<p>If number is dynamic, you may do:</p>

<pre><code>page_content = json_object['query']['pages']
for content in page_content.values():
    my_content = content['thumbnail']['original']
</code></pre>

<p>where <code>my_content</code> is the required information.</p>

python json django urllib