python-backend
/

Python JSON Handling – Working with Data API

Last Sync: Today

On this page

5
0%
5 min read
Remaining
5 minleft

Click any section to jump — progress syncs automatically

python-backend

Python JSON Handling – Working with Data API

JSON in the Python Ecosystem

JSON (JavaScript Object Notation) is the standard format for data exchange between a server and a web or mobile application. As a developer, you'll constantly handle JSON when consuming REST APIs or saving configuration files. Python provides a built-in json module to convert between JSON strings and Python dictionaries/lists.

Key Terminology

  • Serialization (Encoding): Converting a Python object (like a dict) into a JSON-formatted string using json.dumps().
  • Deserialization (Decoding): Converting a JSON string back into a Python object using json.loads().

Basic Operations

The json module makes it easy to switch between types. Note that Python's True, False, and None are automatically mapped to JSON's true, false, and null.

PythonRead-only
1
import json

# 1. Parsing JSON (String to Dict)
json_string = '{"name": "Kishore", "isActive": true}'
user_dict = json.loads(json_string)
print(user_dict["name"]) # Kishore

# 2. Creating JSON (Dict to String)
user_data = {
    "id": 101,
    "skills": ["Flutter", "Python"],
    "verified": False
}
# Use 'indent' for pretty-printing
pretty_json = json.dumps(user_data, indent=4)
print(pretty_json)

Working with Files

When dealing with files (e.g., config.json), use the load() and dump() methods (without the 's'). These operate directly on file streams.

PythonRead-only
1
# Writing to a file
with open('data.json', 'w') as f:
    json.dump(user_data, f)

# Reading from a file
with open('data.json', 'r') as f:
    data = json.load(f)

Data Type Mapping

Python TypeJSON Equivalent
dictobject {}
list, tuplearray []
strstring ""
int, floatnumber
True / Falsetrue / false
Nonenull

Try it yourself

import json

# Complex Python data
project = {
    "title": "Revochamp",
    "version": 1.0,
    "features": ["AI Builder", "Code Gen"],
    "is_beta": True
}

# Convert to JSON with sorting keys
json_output = json.dumps(project, indent=2, sort_keys=True)
print("Encoded JSON:")
print(json_output)

# Back to Python
parsed_data = json.loads(json_output)
print(f"\nProject Title: {parsed_data['title']}")

Test Your Knowledge

Q1
of 3

Which method is used to parse a JSON string into a Python dictionary?

A
json.parse()
B
json.load()
C
json.loads()
D
json.dict()
Q2
of 3

How do you make the output of json.dumps() readable for humans (pretty-print)?

A
Use the 'pretty=True' argument
B
Use the 'indent' argument
C
Use the 'format' argument
D
JSON is always pretty-printed
Q3
of 3

What JSON type does a Python 'None' value convert to?

A
undefined
B
nil
C
null
D
None

Frequently Asked Questions

Why did I get a 'TypeError: Object of type datetime is not JSON serializable'?

The standard JSON module doesn't know how to handle complex Python objects like datetime or custom classes. You must provide a custom encoder function or convert them to strings first.

What is the difference between loads() and load()?

The 's' in loads stands for 'string'. Use loads() for strings and load() for file-like objects.

Is JSON the same as a Python Dictionary?

No. A Dictionary is a Python memory structure; JSON is a text format. While they look similar, JSON has stricter rules (e.g., keys must be double-quoted strings).

Previous

python rest api

Next

flask introduction

Related Content

Need help?

Explore our comprehensive docs or start a chat with our tech experts.