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 Bootcamp: Go from zero to hero in Python

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

{
"gold": 1271,
"silver": 1284,
"platinum": 1270
}

Then parse the JSON object like this:
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

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'])