RPeraltaJr
11/5/2018 - 5:13 AM

Working with JSON

# JSON is commonly used with data APIs. Here's how we can parse JSON into a Python dictionary
# (Do not name file 'json.py')

import json

# ------------------------------------------
# JSON TO DICTIONARY
# ------------------------------------------

# Sample JSON
userJSON = '{"first_name": "John", "last_name":"Doe", "age":30}'

# Parse to dict
user = json.loads(userJSON)

print(user) # {'first_name': 'John', 'last_name': 'Doe', 'age': 30}
print(user['first_name']) # John


# ------------------------------------------
# DICTIONARY TO JSON
# ------------------------------------------

# Same Dictionary
car = {'make': 'Ford', 'model': 'Mustang', 'year': 1970}

# Parse to json
carJSON = json.dumps(car)

print(carJSON)