Working with JSON
Simple interpretation: A list of team members, each member is a data object with name, title, and bio fields. Each field and value provided in the key:value
format.
A list of data objects:
{
"brands":[
{"name":"Apple", "website":"https://apple.com"},
{"name":"Google", "website":"https://google.com"},
{"name":"Microsoft", "website":"https://microsoft.com"}
]
}
Again, each data object contains name-value pairs in a set of { }
.
Summary of JSON (JavaScript Object Annotation)
Single data object:
{
"name":"Fenders Acoustic Guitar",
"category":"Music Instrument",
"price":199.99
}
{ }
to include one data object- Contains
"key":value
pairs- A string or date value in quotes, e.g.
"name":"John"
- A numeric value without quotes, e.g.
"age":33
- A string or date value in quotes, e.g.
- Comma
,
to separate multiple key-value pairs
Data object list:
{
"product":[
{
"name":"Fenders Acoustic Guitar",
"category":"Music Instrument",
"price":199.99
},
{
"name":"Steinway Piano",
"category":"Music Instrument",
"price":28500.00
}
]
}
[ ]
to include multiple data objects,
to separate the objects
Example data in students.json:
[
{
"id":1,
"name":"John Smith",
"program":"IS",
"class_year":2020
},
{
"id":2,
"name":"Albert Einstein",
"program":"DS",
"class_year":2021
},
...
]
Let's first try loading the data:
import json
from pprint import pprint
with open("data/students.json") as f:
# read and parse json data
data = json.loads(f.read())
# print to see if data have been loadedb
pprint(data)
Now that data have been loaded and parsed into the JSON model properly, we can access the data, individual instances and/or attributes in the structure.
For example, if you only want to list student's name
and class_year
for those in the DS
(data science) program:
import json
from pprint import pprint
# read and parse json data
with open("data/students.json") as f:
students = json.loads(f.read())
for student in students:
# filter based on "program"
if student['program'] == 'DS':
# show "name" and "class_year"
print(student['name'], student['class_year'])
More JSON examples can be found at:
References
- Chapter 2 Working with Data, of Hector Cuesta (2013). Practical Data Analysis. https://ebookcentral-proquest-com.ezproxy2.library.drexel.edu/lib/drexel-ebooks/detail.action?docID=1507840
- JSON introduction: https://www.w3schools.com/js/js_json_intro.asp Python API with JSON: https://www.dataquest.io/blog/python-api-tutorial/