Python JSON
gocourse.in Maintenance

We'll be back soon

Our CDN (cdn.gocourse.in) is currently unreachable. Some images, JavaScript, or CSS files may not load properly.

Estimated downtime: ~30 minutes

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

55000

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

{"product": "Mobile", "price": 18000, "brand": "Samsung"}

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

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

Python to JSON Type Conversion Table

Python Type JSON Type
dict Object
list Array
tuple Array
str String
int Number
float Number
True true
False false
None null

Complex Python Object to JSON

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

Example: Convert Complex Data Structure

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

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.

{ "student": "Amit", "age": 21, "is_graduated": false }

Custom Separators

You can customize how keys and values are separated.

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

Sorting JSON Keys

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

{ "age": 21, "is_graduated": false, "student": "Amit" }

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