MCS 260 Fall 2021
lslists files in current directory
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:
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.
json.dump(val,f) to write
val to file object
f as JSON.
Python to JSON type conversion table:
If 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
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.
* But Python's
json module will try to guess when reading.
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:
Let's download it and poke around using Python.
jsonmodule documentation is good and has some helpful examples.