PYTHON

Python JSON: Syntax, Usage, and Examples

JSON is a lightweight text format for storing and sharing data, and Python can easily read and write it using the built-in json module. You’ll use JSON all the time when working with APIs, configuration files, and data exchange between apps.


How to Use JSON in Python

In Python, JSON support comes from the built-in json module. The most common tasks are:

  • Converting JSON strings into Python objects (json.loads())
  • Converting Python objects into JSON strings (json.dumps())
  • Reading JSON from a file (json.load())
  • Writing JSON to a file (json.dump())

Here’s the basic import:

import json

Converting a JSON string into Python data

Use json.loads() when you already have JSON in a string.

import json

json_text ='{"name": "Amina", "age": 28, "member": true}'
data = json.loads(json_text)

print(data)
print(type(data))

That JSON becomes a Python dictionary:

{'name':'Amina','age':28,'member':True}
<class'dict'>

Converting Python data into a JSON string

Use json.dumps() when you want to send data in JSON format, for example in an API request.

import json

user = {"name":"Leo","age":31,"member":False}
json_text = json.dumps(user)

print(json_text)
print(type(json_text))


When to Use JSON in Python

You’ll reach for JSON in Python whenever you need to store or share structured data that can be read by many systems.

1) Working with APIs

Most APIs send responses in JSON. If you call an API and get back a JSON string, you convert it into Python data so you can use it.

A typical API response might include user info, product lists, or search results.

2) Saving configuration data

JSON is popular for config files because it’s readable and easy to edit. You can store settings like:

  • Theme options
  • Feature flags
  • File paths
  • App preferences

3) Storing data between runs

If your script needs to save progress, JSON can be a quick solution. For example:

  • Storing user choices
  • Saving scores in a small game
  • Keeping a list of completed tasks

4) Sending data between services

Python apps often send JSON to other programs, like a front-end app, a database layer, or another server.

JSON works well because JavaScript supports it naturally, and many backend systems do too.


Examples of JSON in Python

Let’s walk through practical examples you’ll likely use in real projects.

Example 1: Parsing JSON from an API response

Imagine you received the following JSON response:

import json

response_text = """
{
  "city": "Podgorica",
  "temperature": 29,
  "conditions": "clear"
}
"""

weather = json.loads(response_text)

print(f"{weather['city']}:{weather['temperature']}°C,{weather['conditions']}")

You can now access keys like weather["temperature"] the same way you do with any dictionary.


Example 2: Writing JSON to a file

Use json.dump() to write data directly into a file.

import json

settings = {
"language":"en",
"dark_mode":True,
"items_per_page":20
}

withopen("settings.json","w")as file:
    json.dump(settings, file)

If you open settings.json, you’ll see something like:

{"language":"en","dark_mode":true,"items_per_page":20}

That works, but it’s a bit hard to read. For nicer formatting, add indentation.

import json

withopen("settings.json","w")as file:
    json.dump(settings, file, indent=2)


Example 3: Reading JSON from a file

Use json.load() to read JSON from a file into Python objects.

import json

withopen("settings.json","r")as file:
    loaded_settings = json.load(file)

print(loaded_settings["items_per_page"])


Example 4: Converting nested Python objects to JSON

JSON supports nested structures, so you can store dictionaries inside lists inside dictionaries.

import json

order = {
"order_id":1042,
"customer": {"name":"Nia","email":"nia@example.com"},
"items": [
        {"product":"Notebook","quantity":2},
        {"product":"Pen","quantity":5}
    ]
}

print(json.dumps(order, indent=2))

This output is easy to use across apps because the structure stays consistent.


Learn More About JSON in Python

Once you know the basics, you’ll run into a few “gotchas” and useful features that can save you a lot of time.

JSON vs Python data types

JSON looks like Python dictionaries and lists, but there are some important differences.

JSON supports:

  • Objects → Python dict
  • Arrays → Python list
  • Strings → Python str
  • Numbers → Python int or float
  • Booleans → Python True and False
  • Null → Python None

Example:

import json

json_text ='{"active": false, "score": null}'
data = json.loads(json_text)

print(data)

Output:

{'active':False,'score':None}


Common JSON mistakes (and how to spot them)

A lot of JSON errors come from small formatting issues. JSON is strict.

Mistake 1: Using single quotes

JSON requires double quotes for strings and keys.

❌ Not valid JSON:

{'name': 'Amina'}

✅ Valid JSON:

{"name":"Amina"}

Mistake 2: Trailing commas

Python allows trailing commas in some places, JSON does not.

❌ Invalid JSON:

{"name":"Leo",}


Handling non-JSON data types in Python

Python can store types that JSON does not support directly, such as:

  • set
  • tuple
  • datetime
  • custom classes

If you try to serialize these with json.dumps(), you’ll get an error.

Example:

import json

data = {"tags": {"python","json"}}
print(json.dumps(data))

That crashes because sets are not JSON serializable.

A simple fix is to convert the set into a list:

import json

data = {"tags":list({"python","json"})}
print(json.dumps(data))


Pretty printing JSON for debugging

Sometimes you just want to see what data looks like.

import json

data = {"name":"Amina","skills": ["Python","SQL","APIs"]}
print(json.dumps(data, indent=2))

This is one of those small “quality of life” tricks you’ll use constantly.


Sorting keys for stable output

If you’re comparing JSON output in logs or tests, sorting keys can help.

import json

data = {"b":2,"a":1}
print(json.dumps(data, sort_keys=True))


Encoding and decoding JSON safely

JSON is usually UTF-8, which supports most characters. If you write JSON to a file and want to keep special characters readable, use ensure_ascii=False.

import json

data = {"city":"Zürich","artist":"Jovana"}
print(json.dumps(data, ensure_ascii=False))

Without that option, Python escapes non-ASCII characters.


Using JSON with HTTP requests

Many Python apps send JSON to an API and parse JSON back from the response. Popular HTTP libraries like requests (third-party) make this easier, but the JSON logic stays the same.

Your code usually looks like this conceptually:

  • Convert Python data → JSON string
  • Send it
  • Receive JSON string
  • Convert JSON string → Python data

Even if you don’t write the HTTP code yourself, knowing json.dumps() and json.loads() helps you understand what’s happening.


Quick checklist for working with JSON

When JSON isn’t behaving, these checks usually solve it fast:

  • Keys and strings use double quotes
  • No trailing commas
  • Data types are JSON-friendly
  • Convert complex Python types before serializing
  • Use indent=2 when you need readability

Summary

JSON is one of the most common data formats you’ll use in Python, especially for APIs and storing structured data. Use json.loads() and json.dumps() for JSON strings, and json.load() and json.dump() for working with files. Once you get comfortable with the data type differences and common formatting rules, JSON becomes one of the easiest tools in your Python workflow.