Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 7.7 — CSV and JSON
Python · Example 3 of 6

JSON: what changes on the round trip

Look at the tuple, the integer key and True/None before and after.

CSV stores tables as lines of comma-separated text and JSON stores nested data as text with objects, arrays, numbers and strings. The csv and json modules read and write them, and they are the two formats you will meet most in data and AI work.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 7 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write parse_scores(text) that takes CSV text with the header name,score and returns a dict that maps each name to its score as an int. Use csv.DictReader and io.StringIO (which makes a string behave like a file). Test it with "name,score\nAsha,90\nBen,75\n".

02

Save {"a": [1, 2, 3], "b": {"c": None}} to a file data.json with indent=2. Read it back with json.load and print data["b"]. Hint: None becomes null in the file.

03

Write save_jsonl(path, records), which writes each record in a list as one JSON line, and load_jsonl(path), which reads them back into a list. Test that loading returns a list equal to the one you saved. Hint: use json.dumps per record and add "\n".

Explain it without notes

01

Why should you use the csv module instead of splitting lines on commas?

02

What is the difference between json.dump, json.dumps, json.load and json.loads?

03

Which Python values cannot be serialised by json.dumps by default, and what are your options?

04

What is JSON Lines and why is it popular for large datasets?

JSON: what changes on the round trip
Sign in to run this example in your browser.

Expected output

{"name": "Jos\u00e9", "tags": ["ml", "python"], "active": true, "boss": null, "1": "one"}
{'name': 'José', 'tags': ['ml', 'python'], 'active': True, 'boss': None, '1': 'one'}
{
  "name": "José",
  "scores": [
    90,
    85
  ]
}
José 175