This notebook contains an excerpt from the Python Programming and Numerical Methods - A Guide for Engineers and Scientists, the content is also available at Berkeley Python Numerical Methods.

The copyright of the book belongs to Elsevier. We also have this interactive book online for a better learning experience. The code is released under the MIT license. If you find this content useful, please consider supporting the work on Elsevier or Amazon!

# JSON Files¶

JSON is another format we are going to introduce. It stands for JavaScript Object Notation. A JSON file usually ends with extension “.json”. Unlike pickle, which is Python dependent, JSON is a language-independent data format, which makes it attractive to use. Besides, it is usually takes less space on the disk and the manipulation is faster than pickle (if you are interested, search online to find more materials about it). Therefore, it is a good option to store your data using JSON. In this section, we will briefly explore how to handle JSON files in Python.

## JSON format¶

The text in JSON is done through quoted string containing value in key-value pairs within {}. It is actually very similar to the dictionary we saw in Python. For example:

{
"school": "UC Berkeley",
"city": "Berkeley",
"state": "California",
"postal": "94720"
},

"list":[
"student 1",
"student 2",
"student 3"
]
}


## Write a JSON file¶

In Python, the easiest way to handle JSON is to use json library. There are some other libraries such as simplejson, jyson etc. In this section, we will use json which is natively supported by Python to write and load JSON files.

TRY IT! Create a dictionary, and save it to a JSON file on disk. To use a pickle, we need to import the module first.

import json

school = {
"school": "UC Berkeley",
"city": "Berkeley",
"state": "California",
"postal": "94720"
},

"list":[
"student 1",
"student 2",
"student 3"
],

"array":[1, 2, 3]
}
json.dump(school, open('school.json', 'w'))


To use json to serialize an object, we use the json.dump function, which takes two arguments: the first one is the object, and the second argument is a file object returned by the open function. Note here the mode of the open function is ‘w’ which indicates write file.

Now let us load the JSON file we just saved on the disk back using the json.load function.
my_school = json.load(open('./school.json', 'r'))

We can see the use of json is actually very similar to pickle in the last section. JSON supports different types, like strings and numbers, as well as nested lists, tuples and objects, we will leave this for you to explore further.