Files and JSON
with open, encoding and exchanging data as JSON.
Files are opened with the open function inside a with statement. It guarantees that the file is closed, even if an error happens along the way:
with open("notes.txt", "w", encoding="utf-8") as file:
file.write("first line\n")
with open("notes.txt", encoding="utf-8") as file:
for line in file:
print(line.strip())
The "w" mode overwrites the file, "a" appends to the end, and without a mode the file is opened for reading. Always pass encoding="utf-8". Without it, text with non-Latin letters is read differently on different systems. Files are not available in the learning sandbox, so this lesson's task works with a JSON string.
JSON is a text format for exchanging data that almost every language and service understands. The json module turns Python structures into text and back:
import json
data = {"name": "Ann", "tags": ["admin", "dev"], "active": True}
text = json.dumps(data)
print(text) # {"name": "Ann", "tags": ["admin", "dev"], "active": true}
print(json.loads(text)["tags"][0]) # admin
A dictionary becomes a JSON object, a list becomes an array, True becomes true, None becomes null. Keys in JSON are always strings.
json.dumps(data, ensure_ascii=False, indent=2) keeps non-Latin letters as they are and makes the text readable with indentation. json.load(file) and json.dump(data, file) work directly with an open file.
Check data from external JSON like any other input. The key you need may be missing, and a string may arrive instead of a number. On malformed text json.loads raises json.JSONDecodeError, a subclass of ValueError.
Practice
Why with
Why open a file with with open(...) as file?
- The file is closed automatically, even on an error
- Without with the file cannot be read
- with reads the file faster
- with picks the encoding by itself
Into JSON
What does the program print?
import json print(json.dumps({"ok": True, "n": None}))An order total
Write a function order_total(text): the input is a JSON array of items of the form {"price": 10, "qty": 2}, and the function returns the total of the order.