Python – Count JSON elements before extracting data

Question:

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.

Asked By: Hyperion

||

Answers:

You didn’t need to know the length of the result, you are fine with a for loop:

for result in z['results']:
    # process the results here

Anyway, if you want to know the length of ‘results’: len(z.results)

Answered By: fasouto

If you want to get the length, you can try:

len(z['result'])

But in python, what we usually do is:

for i in z['result']:
    # do whatever you like with `i`

Hope this helps.

Answered By: crsxl

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"])
Answered By: LexyStardust

You don’t need, or likely want, to count them in order to loop over them, you could do:

import json
import urllib2

u = urllib2.urlopen('myapiurl')
z = json.load(u)
u.close
for result in z['results']:
    link = result['source_link']
    title = result['source_link/_title']
    # do something with link/title

Or you could do:

u = urllib2.urlopen('myapiurl')
z = json.load(u)
u.close
link = [result['source_link'] for result in z['results']]
title = [result['source_link/_title'] for result in z['results']]
# do something with links/titles lists
Answered By: CrazyCasta

Few pointers:

  1. No need to know results‘s length to iterate it. You can use for result in z['results'].
  2. lists start from 0.
  3. If you do need the index take a look at enumerate.
Answered By: Reut Sharabani

use this command to print the result on the terminal and then can check the number of results

print(len(z['results'][0]))
Answered By: Sujith Jeewantha
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.