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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
{ "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.
1 2 3 4 5 6 7 |
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.
1 |
[{'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.
1 2 3 4 5 6 7 8 9 |
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.
1 2 |
black white |