Working with JSON in Python

What is JSON?

JSON (JavaScript Object Notation) is a simple format for storing and exchanging data. It is easy to read and write for both humans and machines. Python has a built-in module that allows us to work with JSON data easily called json.

Using JSON in Python

Importing the JSON Module

To start using JSON in Python, you first need to import the json module:

Tutorials dojo strip

Parsing JSON

You can convert a JSON string into a Python dictionary using the json.loads() function.

Example:

Converting Python to JSON

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

Example:

Supported Data Types

Dictionary (dict)JSON Object
ListJSON Array
TupleJSON Array
StringJSON String
IntegerJSON Number
FloatJSON Number
Boolean (True/False)JSON true/false
NoneJSON null
You can convert various Python objects to JSON, including dictionaries, lists, and more.

Example:

Formatting JSON Output

To format the JSON output for better readability, use indentation.

Example:

Sorting JSON Keys

You can sort the keys in your JSON output using the sort_keys parameter.

Example:

Tutorials dojo strip