DEV Community

Shahrouz Nikseresht
Shahrouz Nikseresht

Posted on

Working with JSON in Python Explained Simply

JSON (JavaScript Object Notation) is a common format for storing and exchanging data. Python's json module makes it easy to work with JSON.

What is JSON?

JSON looks similar to Python dictionaries and lists.

Example JSON data:

{
    "name": "Alex",
    "age": 25,
    "hobbies": ["reading", "coding", "hiking"],
    "is_student": false
}
Enter fullscreen mode Exit fullscreen mode

Importing the json module

Always import json first:

import json
Enter fullscreen mode Exit fullscreen mode

Converting Python to JSON (serializing)

Use json.dumps() for a string or json.dump() for a file.

To string:

data = {
    "name": "Alex",
    "age": 25,
    "hobbies": ["reading", "coding"]
}

json_string = json.dumps(data)
print(json_string)
# {"name": "Alex", "age": 25, "hobbies": ["reading", "coding"]}
Enter fullscreen mode Exit fullscreen mode

Pretty print with indentation:

pretty_json = json.dumps(data, indent=4)
print(pretty_json)
Enter fullscreen mode Exit fullscreen mode

To file:

with open("data.json", "w") as file:
    json.dump(data, file, indent=4)
Enter fullscreen mode Exit fullscreen mode

Converting JSON to Python (deserializing)

Use json.loads() for a string or json.load() for a file.

From string:

json_string = '{"name": "Sam", "age": 30}'

data = json.loads(json_string)
print(data["name"])  # Sam
Enter fullscreen mode Exit fullscreen mode

From file:

with open("data.json", "r") as file:
    data = json.load(file)

print(data["hobbies"])  # ['reading', 'coding']
Enter fullscreen mode Exit fullscreen mode

Simple examples

Save a list of users to JSON:

users = [
    {"name": "Alex", "age": 25},
    {"name": "Sam", "age": 30}
]

with open("users.json", "w") as file:
    json.dump(users, file, indent=4)
Enter fullscreen mode Exit fullscreen mode

Read and print names:

with open("users.json", "r") as file:
    users = json.load(file)

for user in users:
    print(user["name"])
Enter fullscreen mode Exit fullscreen mode

Important notes

  • JSON keys must be strings.
  • Supported types: dict, list, str, int, float, bool, None.
  • Use indent for readable files.
  • Handle errors with try/except (e.g., invalid JSON or file not found).

Quick summary

  • Import json to work with JSON data.
  • dumps() and dump() convert Python to JSON.
  • loads() and load() convert JSON to Python.
  • Use indentation for human-readable output.
  • JSON is perfect for configuration files and web APIs.

Practice saving and loading small data structures as JSON. It is essential for data exchange in Python programs.

Top comments (0)