Learn how to parse JSON objects with python.

JavaScript Object Notation (JSON) is a data exchange format. While originally designed for JavaScript, these days many computer programs interact with the web and use JSON.

Interacting with the web is mostly done through APIs (Application Programmable Interface), in JSON format.

Related course: Complete Python Programming Course & Exercises

python JSON example

Parse JSON

You can parse a JSON object with python. The object will then be converted to a python object.

Start by creating a json object

1
2
3
4
5
{
"gold": 1271,
"silver": 1284,
"platinum": 1270
}

Then parse the JSON object like this:
1
2
3
import json
obj = json.loads('{"gold": 1271,"silver": 1284,"platinum": 1270}')
print(obj['gold'])

Parse JSON from URL

You can get JSON objects directly from the web and convert them to python objects. This is done through an API endpoint

1
2
3
4
5
6
7
8
9
10
11
12
13
import json
import urllib.request

# download raw json object
url = "https://api.gdax.com/products/BTC-EUR/ticker"
data = urllib.request.urlopen(url).read().decode()

# parse json object
obj = json.loads(data)

# output some object attributes
print('$ ' + obj['price'])
print('$ ' + obj['volume'])