Bootstrap FreeKB - Python (Scripting) - Loop through JSON list
Python (Scripting) - Loop through JSON list

Updated:   |  Python (Scripting) articles

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/python3
import json

raw_json = '{"foo":"Hello","bar":"World"}'

try:
  parsed_json = json.loads(raw_json)
except Exception as exception:
  print(f"Got the following exception: {exception}")

for key in parsed_json:
  print("key = {key}")

 

Which should produce the following.

key = foo
key = bar

 

Let's say you have JSON like this. The main key is an list, 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/python3
import json

file = open("example.json")

try:
  parsed_json = json.load(file)
except Exception as exception:
  print(f"Got the following exception: {exception}")

file.close()

print(parsed_json['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/python3
import json
raw_json = '{ "main": [ { "foo": "Hello", "bar": "World" } ] }'

try:
  parsed_json = json.loads ( raw_json )
except Exception as exception:
  print(f"Got the following exception: {exception}")

for item in parsed_json["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 list.

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

 

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

#!/usr/bin/python3
import json

file = open("example.json")

try:
  parsed_json = json.load(file)
except Exception as exception:
  print(f"Got the following exception: {exception}")

file.close()

print(parsed_json['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/python3
import json
file = open('/path/to/example.json')

try:
  parsed_json = json.load(file)
except Exception as exception:
  print(f"Got the following exception: {exception}")

file.close()

for main in parsed_json['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



Comments


Add a Comment


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