Course 2.1Lesson 4 of 5
JSON is a text format for whole structures: dictionaries, lists, texts, numbers, True, False and None, nested as deep as you like. json.dumps turns a structure into a text and json.loads turns a text back, and json.dump and json.load do the same with a file. indent makes the text neat for people. JSON cannot keep everything exactly: a tuple comes back as a list, a key that is a number comes back as a text, and a set cannot be saved at all, which is a TypeError. Text that is not valid JSON raises a JSONDecodeError. A good pattern is to load the data, change it, and save it, with a default value when the file is missing or damaged.
Try the code and the simulations beside the lesson.
After this lesson you can
load that survives a missing or damaged file.CSV is good for flat tables. But your data may have structure: a student with a name, an age, and a list of marks. A table cannot hold a list in a cell without tricks. For this, there is JSON: a text format for dictionaries and lists, nested as deep as you like. It looks very much like the Python you write. Almost every program in the world can read it, so it is the usual way to pass data between programs and websites.
Predict first. What will json.dumps(student) look like? Then run it.
json.dumps(student) turns a structure into a text. (The s stands for string.) The text looks like the dictionary, but with true and null in small letters, and only double quotation marks.json.dumps(student, indent=2) makes a neat version for people to read, with each part on its own line.json.loads(text) goes the other way: text to structure. After the round trip, back == student is True, and we can use back["marks"][1], which is 85, as a number.json.dump(data, f) and json.load(f) (no s) write to and read from a file. Learn the pair: dumps and loads use texts, dump and load use files.{}, a list becomes an array [], True becomes true, None becomes null.JSON is a format for text, and it has only a few kinds of value. So some Python values change on the way.
So before you save, think: does my data use only dictionaries with text keys, lists, texts, numbers, True, False and None? If so, JSON keeps it exactly. If not, convert it, and convert it back after loading.
The most common use of JSON in a small program is a database in a file: load it at the start, change it, save it back.
The demonstration runs the pattern twice. The second time starts from the file, as a later run of the program would. Asha's 72 becomes 82. Then the file is damaged on purpose, and load gives the default instead of an error.
A caution: if the program stops in the middle of save, the file can be left half written. Real programs write to a temporary file first and then rename it. For a small book, the simple way is fine.
The pattern is always the same: load, change, save. The default in load() covers the first run, when the file does not exist yet.
| CSV | JSON | |
|---|---|---|
| Shape | a flat table | nested lists and dictionaries |
| Types | everything is text | numbers, text, booleans, null, lists, objects |
| Opens in a spreadsheet | yes | no |
| Good for | data that is a table | data with structure |
dump and dumps. The s means a string, and no s means a file.TypeError. Use a list.JSONDecodeError.load that does not handle a missing file."w" to read it. It empties the file.Start with two quick questions. Each New numbers gives you a fresh one, so you can practise as long as you like.
Then the labs and the problems:
json.dumps and json.loads use texts. json.dump and json.load use files.True, False and None.Try each one on your own first. If you are stuck, open a hint. Then check with Show the answer.
json.loads(json.dumps((1, 2))) give?json.dump and json.dumps?load take a default value?Every lesson is open to read. Enrolling also lets you:
Log in to join the discussion.
Loading…
This lesson is free to read. Enroll free to keep your place and take the tests.