Python JSON

Python JSON

Kishore V


Python JSON

JSON (JavaScript Object Notation) is a lightweight format used to store and exchange data.

It is text-based, easy to read, and widely used in APIs, configuration files, and web applications.

Working with JSON in Python

Python includes a built-in module named json that allows you to easily read, write, and manipulate JSON data.

Importing the JSON Module

import json

Parsing JSON (JSON → Python)

When you receive data in JSON format, it is usually a string.

To convert this JSON string into a Python object, use the json.loads() method.

Example: Convert JSON String to Python Dictionary

Output:

55000
Try it Yourself

After parsing, the JSON data becomes a Python dictionary, which you can access using keys.

Converting Python to JSON (Python → JSON)

To convert a Python object into a JSON string, use the json.dumps() method.

Example: Convert Python Dictionary to JSON

Output:

{"product": "Mobile", "price": 18000, "brand": "Samsung"}
Try it Yourself

The output is a JSON-formatted string, ready to be stored or sent over a network.

Supported Python Data Types

The following Python data types can be converted into JSON:

    • dict

    • list

    • tuple

    • str

    • int

    • float

    • True

    • False

    • None

Example: Convert Multiple Python Types to JSON

Output:

{"course": "Python", "level": "Beginner"}
["HTML", "CSS", "JavaScript"]
["Red", "Green", "Blue"]
"Welcome"
99
45.6
true
false
null
Try it Yourself

Python to JSON Type Conversion Table

Python Type JSON Type
dictObject
listArray
tupleArray
strString
intNumber
floatNumber
Truetrue
Falsefalse
Nonenull

Complex Python Object to JSON

Python dictionaries can contain nested data such as lists, tuples, and other dictionaries.

Example: Convert Complex Data Structure

Output:

{"student": "Amit", "age": 21, "is_graduated": false, "subjects": ["Maths", "Science", "English"], "address": null, "devices": [{"type": "Laptop", "brand": "HP"}, {"type": "Phone", "brand": "OnePlus"}]}
Try it Yourself

Formatting JSON Output

Raw JSON strings are difficult to read.

The json.dumps() method provides parameters to format the output.

Using Indentation

The indent parameter adds line breaks and indentation for better readability.

Output:

{
    "student": "Amit",
    "age": 21,
    "is_graduated": false
}
Try it Yourself

Custom Separators

You can customize how keys and values are separated.

Output:

{
    "student" => "Amit" |
    "age" => 21 |
    "is_graduated" => false
}
Try it Yourself

Sorting JSON Keys

To display JSON keys in alphabetical order, use the sort_keys parameter.

Output:

{
    "age": 21,
    "is_graduated": false,
    "student": "Amit"
}
Try it Yourself

Our website uses cookies to enhance your experience. Learn More
Accept !