5.5. Working with Nested Data Structures¶
Storing information in a nested data structure has become a common practice. This allows information to be collected in one structure while still allowing the most appropriate data structure for storing each different types of information internally.
One popular standard format for storing such information is JSON, which stands for JavaScript Object Notation. An example of data stored in the JSON format is presented below.
{
"firstName": "John",
"lastName": "Smith",
"isAlive": true,
"age": 25,
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021-3100"
},
"phoneNumbers": {
"home": {
"type": "home",
"number": "212 555-1234"
},
"office":{
"type": "office",
"number": "646 555-4567"
},
"modile":{
"type": "mobile",
"number": "123 456-7890"
}
},
"children": ["Alice", "Ben"],
"spouse": null
}
Source
This example was adapted from the Wikipedia JSON page which is shared under the Creative Commons Attribution-ShareAlike License.
Notice that the JSON data structure consists of literal values (string, numbers, JavaScript booleans, null, etc.) inside of data structures that look remarkably similar to Python lists and dictionaries.
Note
The json
module also has functions for reading and writing JSON to a file
(load
and dump
, repectively).
5.5.1. Reading JSON data into Python¶
Python can read a JSON file with only a few changes to the data. This is
typically accomplished using the json standard module. In this case, we will use
the loads
function from json
to load the JSON data using a (multiline)
string.
In [1]: from json import loads
In [2]: s = '''
...: {
...: "firstName": "John",
...: "lastName": "Smith",
...: "isAlive": true,
...: "age": 25,
...: "address": {
...: "streetAddress": "21 2nd Street",
...: "city": "New York",
...: "state": "NY",
...: "postalCode": "10021-3100"
...: },
...: "phoneNumbers": {
...: "home": {
...: "type": "home",
...: "number": "212 555-1234"
...: },
...: "office":{
...: "type": "office",
...: "number": "646 555-4567"
...: },
...: "mobile":{
...: "type": "mobile",
...: "number": "123 456-7890"
...: }
...: },
...: "children": ["Alice", "Ben"],
...: "spouse": null
...: }'''
...:
In [3]: data = loads(s)
In [4]: type(data)
Out[4]: dict
In [5]: data