MCS 260 Fall 2021
Emily Dumas
ls lists files in current directoryJSON stands for JavaScript object notation. It is a format for storing various types of data in text files. Many languages can read and write this format.
Python has a module for reading and writing JSON.
By using that module, you can move various types of data in and out of files cleanly, without needing to handle the read/write details yourself.
Supported basic types:
true, false.None.Supported composite types:
list. Surrounded by square brackets, values separated by commas.dict. Surrounded by curly braces, comma separator. Keys must be strings.A JSON file must contain a single value. Most often it is an object or array.
Import the module json to make JSON function available.
You'll need to open a file yourself; JSON functions expect a file object.
Use json.dump(val,f) to write val to file object f as JSON.
Python to JSON type conversion table:
dict → objectlist or tuple → arrayint or float → numberbool → booleanNone → nullIf you want to handle writing yourself, you can ask the JSON module to convert a value to a JSON string, e.g.
json.dumps(val) # make JSON string out of val
Use json.load(f) to interpret contents of file object f as JSON and return the decoded result.
json.loads(text) will instead process string text as JSON.
int and float*tuple and list* But Python's json module will try to guess when reading.
Let's modify wordstats3file.py so that it writes a dictionary of statistics to a JSON file.
That way, another program can read and use the report easily without concern for formatting details.
One of the items in that list is a data file listing episodes of the Netflix TV show Stranger Things. The link to it is actually broken, but the list is available at:
https://api.tvmaze.com/shows/2993/episodes
Let's download it and poke around using Python.
json module documentation is good and has some helpful examples.