Python (Scripting) - Loop through JSON array

There are several built in modules that are part of the Python Standard Library included with your Python installation, such as os (Operating System) and re (Regular Expression) and sys (System).

Let's say you have the following.

#!/usr/bin/python
import json

raw_json = '{"foo":"Hello","bar":"World"}'
data = json.loads(raw_json)

for key in data:
  print("key = " + str(key))

 

Which should produce the following.

key = foo
key = bar

 

Let's say you have JSON like this. The main key is an array, as indicated by the [ ] characters.

{
  "main": [
    { 
       "foo": "Hello",
       "bar": "World"
    },
    { 
       "foo": "Goodbye",
       "bar": "Earth"
    }
  ]
}

 

And you are parsing the JSON using json.load or using json.loads, perhaps like this.

#!/usr/bin/python
import json

file = open("example.json")
data = json.load(file)
file.close()

print(data['main'])

 

Running this script should print the following.

[{u'foo': u'Hello', u'bar': u'World'}, {u'foo': u'Goodbye', u'bar': u'Earth'}]

 

Here is how you can print a certain item using index numbers. This should print "Hello".

print(data['main'][0]['foo'])

 

And here is how you could loop through the main key.

#!/usr/bin/python
import json
raw_json = '{ "main": [ { "foo": "Hello", "bar": "World" } ] }'
data = json.loads ( raw_json )

for item in data["main"]:
  print(item["foo"])
  print(item["bar"])

 

Running this script should return the following.

~]# python example.py
Hello
World
Goodbye
Earth

 

Let's say you have a nested array.

{
  "main": [
    {
       "sub": [
         { 
           "foo": "Hello",
           "bar": "World"
        }
      ]
    }
  ]
}

 

And you print the content of the "main" key.

#!/usr/bin/python
import json

file = open("example.json")
data = json.load(file)
file.close()

print(data['main'])

 

Which should produce the following.

[{u'sub': [{u'foo': u'Hello', u'bar': u'World'}]}]

 

Here is how you could loop through the main key, loop through the sub key, and print the values of the foo and bar keys.

#!/usr/bin/python
import json
file = open('/path/to/example.json')
data = json.load(file)
file.close()

for main in data['main']:
  for item in main['sub']:
    print(item['foo'])
    print(item['bar'])

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee

Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.





Please enter 91cf0 in the box below so that we can be sure you are a human.