~/learn/Python · Text & files

JSON and CSV

Parse the two formats data arrives in.

8 min readlesson 15 of 23jsoncsvparsing

why this matters

APIs return JSON and colleagues send CSVs. These two formats cover almost every file you will ever be handed.

json.loads turns a JSON string into Python objects and json.dumps goes the other way. Nested structures become nested dicts and lists.

python · editable
loading editor…

Try it: Add a 'score' key set to 10 and print the JSON again.

csv.DictReader reads rows as dictionaries keyed by the header. Here we read from a string so the example runs in the browser; in a script you would pass an open file instead.

python · editable
loading editor…

Note

Always convert CSV values explicitly — everything arrives as a string, and silently summing strings is a classic bug.

loads vs load

json.loads reads a string, json.load reads a file. Mixing them up gives a confusing 'expected str' error.

Pro tip

Use csv.DictReader instead of csv.reader — you get dictionaries keyed by header name instead of fragile positions.

key takeaways

  • JSON maps to dicts and lists directly.
  • loads/dumps for strings, load/dump for files.
  • DictReader gives you named columns.

check your understanding

You have JSON in a Python string. Which converts it to a dict?

free practice

Build confidence with a question you can solve without Pro.