Hyperion Hyperion - 3 months ago 27
JSON Question

Python - Count JSON elements before extracting data

I use an API which gives me a JSON file structured like this:

{
offset: 0,
results: [
{
source_link: "http://www.example.com/1",
source_link/_title: "Title example 1",
source_link/_source: "/1",
source_link/_text: "Title example 1"
},
{
source_link: "http://www.example.com/2",
source_link/_title: "Title example 2",
source_link/_source: "/2",
source_link/_text: "Title example 2"
},
...


And I use this code in Python to extract the data I need:

import json
import urllib2

u = urllib2.urlopen('myapiurl')
z = json.load(u)
u.close
link = z['results'][1]['source_link']
title = z['results'][1]['source_link/_title']


The problem is that to use it I have to know the number of the element from which I'm extracting the data. My
results
can have different length every time, so what I want to do is to count the number of elements in
results
at first, so I would be able to set up a loop to extract data from each element.

Answer

To check the length of the results key:

len(z["results"])

But if you're just looping around them, a for loop is perfect:

for result in x["results"]:
    print(result["source_link"])