Read JSON and CSV
Turn structured text into dictionaries and rows.
JSON represents nested data with objects, arrays, and primitive values. json.loads() decodes a string into Python values and json.dumps() encodes Python values as JSON text. Use json.load() to read from an open file.
CSV represents rows with columns. csv.DictReader uses the header as keys and handles quoted fields. CSV fields are strings, so convert a numeric column with int() or float() before doing arithmetic.
The header names the two fields available in every row.
Try it yourself
Add a CSV row for water with a count of 4. Print the new total as JSON.
Target output
{"total": 9}Show a hint
Add water,4 followed by a newline to the text. The existing calculation handles the extra row.
Ready
Run your code to see the output here.
The first run downloads Python. Code runs in your browser. Progress and drafts are stored on this device.
Show one solution
import csv
import io
import json
text = "item,count\ntea,3\ncoffee,2\nwater,4\n"
rows = csv.DictReader(io.StringIO(text))
total = sum(int(row["count"]) for row in rows)
print(json.dumps({"total": total}))