Hyperion Hyperion - 1 year ago 115
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)
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
can have different length every time, so what I want to do is to count the number of elements in
at first, so I would be able to set up a loop to extract data from each element.

Answer Source

To check the length of the results key:


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

for result in x["results"]: