Skip to main content

Python JSON: Parse, Create, and Manipulate JSON Data

Intermediate25 min6 exercises85 XP
0/6 exercises

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.

A JSON string in Python
Loading editor...
There are a few important differences between JSON and Python:
--------------
true / falseTrue / False
nullNone
Keys must be strings in double quotesKeys can be any hashable type
Only double quotes for stringsSingle or double quotes

How Do You Convert Between JSON and Python?

The json module gives you two main functions for working with JSON strings:

  • `json.loads()` — Converts a JSON string into a Python object (usually a dictionary or list). Think "load string."
  • `json.dumps()` — Converts a Python object into a JSON string. Think "dump string."
  • Parsing JSON with json.loads()

    json.loads() turns a JSON string into a Python dict
    Loading editor...

    Notice that true in JSON became True in Python. The json module handles all the conversions automatically.

    Creating JSON with json.dumps()

    json.dumps() turns a Python dict into a JSON string
    Loading editor...

    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.

    json.dump() and json.load() work with file objects
    Loading editor...

    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.

    String functions (loads/dumps)
    # Work with strings in memory
    data = json.loads(json_string)
    json_string = json.dumps(data)
    File functions (load/dump)
    # 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.

    Pretty printing with indent parameter
    Loading editor...

    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.

    Sorting keys alphabetically
    Loading editor...

    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.

    Navigating nested JSON from an API response
    Loading editor...

    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.

    Using .get() for safe access
    Loading editor...

    How Does Python Map JSON Types?

    Python's json module automatically converts between JSON types and Python types:

    JSON to Python type mapping
    Loading editor...

    Practice Exercises

    Parse a JSON String
    Write Code

    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:

    London
    Loading editor...
    Predict the JSON Output
    Predict Output

    What 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)
    Loading editor...
    Create Pretty JSON
    Write Code

    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.

    Loading editor...
    Fix the JSON Parsing Bug
    Fix the Bug

    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: Python
    Loading editor...
    Refactor String Concatenation to json.dumps
    Refactor

    This 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]}
    Loading editor...
    Extract Data from Nested API JSON
    Write Code

    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
    Loading editor...