Python JSON: Parse, Create, and Manipulate JSON Data
Imagine a universal language that every app, website, and database can understand. That's JSON (JavaScript Object Notation). It's the most popular format for sending data between computers.
When you check the weather on your phone, the app sends a request to a server. The server sends back data in JSON format — the temperature, humidity, forecast, all neatly structured. Your app reads that JSON and shows it on screen.
Python has a built-in json module that makes it easy to convert between Python objects (dictionaries, lists) and JSON strings. In this tutorial, you'll learn how to read, write, and manipulate JSON data.
What Does JSON Look Like?
JSON looks a lot like a Python dictionary. It uses curly braces, key-value pairs, and supports strings, numbers, booleans, lists, and nested objects.
| There are a few important differences between JSON and Python: | |
|---|---|
| ------ | -------- |
true / false | True / False |
null | None |
| Keys must be strings in double quotes | Keys can be any hashable type |
| Only double quotes for strings | Single or double quotes |
How Do You Convert Between JSON and Python?
The json module gives you two main functions for working with JSON strings:
Parsing JSON with json.loads()
Notice that true in JSON became True in Python. The json module handles all the conversions automatically.
Creating JSON with json.dumps()
See how Python's True became true and single quotes became double quotes? The json.dumps() function produces valid JSON every time.
How Do You Read and Write JSON Files?
When working with files, use json.load() (no s) to read and json.dump() (no s) to write. They work with file objects instead of strings.
On a real system, you'd use open() instead of StringIO. The pattern is the same: json.dump(data, file_object) to write, and json.load(file_object) to read.
# Work with strings in memory
data = json.loads(json_string)
json_string = json.dumps(data)# Work with file objects
data = json.load(file_obj)
json.dump(data, file_obj)How Do You Make JSON Human-Readable?
By default, json.dumps() squishes everything onto one line. For debugging or config files, you want nicely formatted JSON with indentation.
The indent parameter sets how many spaces to use for each level of nesting. indent=2 and indent=4 are the most common choices.
You can also sort the keys alphabetically with sort_keys=True. This is useful when you want consistent output for testing or version control.
How Do You Work with Complex JSON Structures?
Real-world JSON from APIs is often nested — dictionaries inside lists inside dictionaries. The key skill is navigating these structures step by step.
The trick is to work from the outside in. First access data['results'] to get the list. Then loop through the list and access each item's keys.
Safely accessing nested data
What if a key might be missing? Use the .get() method with a default value to avoid KeyError exceptions.
How Does Python Map JSON Types?
Python's json module automatically converts between JSON types and Python types:
Practice Exercises
You are given a JSON string stored in json_str. Parse it into a Python dictionary and print the value of the 'city' key.
json_str = '{"city": "London", "population": 9000000}'Expected output:
LondonWhat does this code print? Pay attention to how Python types map to JSON.
import json
data = {'active': True, 'score': None}
result = json.dumps(data)
print(result)Create a Python dictionary with keys 'name' (value 'Alice'), 'age' (value 25), and 'hobbies' (value ['reading', 'hiking']). Convert it to a pretty-printed JSON string with 2-space indentation and print it.
This code tries to parse a JSON string and print a nested value, but it crashes. Fix the bug so it prints the expected output.
Expected output:
Language: PythonThis code manually builds a JSON string using string concatenation, which is error-prone. Refactor it to use json.dumps() instead. The output should be identical.
Expected output:
{"name": "Bob", "scores": [90, 85, 92]}You are given a JSON string representing an API response with a list of users. Parse it and print each user's name and their first hobby.
The JSON data:
{"users": [{"name": "Alice", "hobbies": ["chess", "piano"]}, {"name": "Bob", "hobbies": ["soccer", "cooking"]}, {"name": "Charlie", "hobbies": ["painting", "yoga"]}]}Expected output:
Alice likes chess
Bob likes soccer
Charlie likes painting