How to import JSON data in Python

The following post will show you how to load and read a JSON document using the ‘json’ module.

Lets us use the following example json.

{
  "colors": [
    {
      "color": "black",
      "category": "hue",
      "type": "primary",
      "code": {
        "rgba": [255,255,255,1],
        "hex": "#000"
      }
    },
    {
      "color": "white",
      "category": "value",
      "code": {
        "rgba": [0,0,0,1],
        "hex": "#FFF"
      }
    }
	]
}

The following will load the document which stored the above json data and iterates over the json object to print the data.

import json
json_data = open('sample-data.json').read()

data = json.loads(json_data)

for item in data:
    print(data[item])

This will output the following.

[{'color': 'black', 'category': 'hue', 'type': 'primary', 'code': {'rgba': [255, 255, 255, 1], 'hex': '#000'}}, {'color': 'white', 'category': 'value', 'code': {'rgba': [0, 0, 0, 1], 'hex': '#FFF'}}]

To go down to individual element levels we can do the following.

import json
json_data = open('sample-data.json').read()

data = json.loads(json_data)

for item in data:
    nodes = data[item]
    for node in nodes:
        print(node['color'])

This will print the following.

black
white

Leave a Reply

Your email address will not be published. Required fields are marked *