Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Count JSON elements before extracting data

Tags:

python

json

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.

like image 972
Hyperion Avatar asked Jul 03 '15 10:07

Hyperion


People also ask

How do you count elements in JSON Python?

USE len() TO COUNT THE ITEMS IN A JSON OBJECT. Call len(obj) to return the number of items in a JSON object obj.

How do you count items in a JSON array?

If you want to count array elements in individual JSON strings, you can echo these and pipe the output to jq : echo '[{“username”:”user1″},{“username”:”user2″}]' | jq '. Counting Array Elements from File. Counting Elements in Nested Arrays.

How do you count the number of keys in a JSON object?

keys() method and the length property are used to count the number of keys in an object. The Object. keys() method returns an array of a given object's own enumerable property names i.e. ["name", "age", "hobbies"] . The length property returns the length of the array.


2 Answers

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"])
like image 117
LexyStardust Avatar answered Oct 24 '22 08:10

LexyStardust


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)

like image 32
fasouto Avatar answered Oct 24 '22 08:10

fasouto