Menu Close

Mastering Python JSON Module (Examples)

Python JSON MODULE MASTERY

Hello Programmer, In this article, we are going to learn about the Python JSON module along with various examples. Python JSON module provides a facility to work with JSON data. The json module in Python provides a simple and easy way to encode and decode data in JSON (JavaScript Object Notation) format.

Here we will see how to convert a Python Dictionary to JSON and vice-versa step by step.

At the end of this Python JSON module tutorial, you are completely able to work with the Python JSON module. In previous tutorials, we have seen lots of Python built-in modules along with examples.

Python JSON Module – A Comprehensive Guide

Throughout this Python JSON Module tutorial, we will cover all the mentioned points below.

  • What is JSON?
  • Why Use JSON in Python?
  • JSON Module Basics
  • JSON Encoding and Decoding
  • json Module Functions
  • Examples and Use Cases
  • Handling Errors
  • Additional Information
  • Conclusion

What is JSON?

JSON stands for JavaScript Object Notation. JSON is a data format that is used for representing structured data. JSON is commonly used to send and receive data between server and client.

You should have remembered some important points of JSON.

  • JSON stands for JavaScript Object Notation.
  • JSON is used for transmitting data between server and client.
  • JSON is text, written in JavaScript Object Notation.
  • JSON is the syntax for storing and exchanging data.
  • JSON is the most popular data format used for representing data structure.

Example of JSON Object:

{
  "name": "John Doe",
  "age": 30,
  "is_employee": true,
  "skills": ["Python", "Django", "Machine Learning"]
}

Why Use JSON in Python?

These are some reasons to use JSON Module in Python.

  • Interoperability: JSON is used by many web APIs for sending and receiving data.
  • Portability: JSON is language-agnostic, making it ideal for cross-platform data exchange.
  • Simplicity: It is easy to read and write for both humans and machines.
  • Serialization: Python objects can be easily serialized into JSON and sent across networks or saved in files.

JSON Module Basics

The Python json module provides two main functions for working with JSON data:

  • json.dumps() for converting Python objects to JSON (serialization).
  • json.loads() for converting JSON strings back to Python objects (deserialization).

To use the json module, simply import it:

import json

Python JSON loads()

To convert JSON into Python object, use json.loads() method.

Example: Converting JSON to Python Object

import json

# json 
x = '{"name": "Programming", "tutorial": "Python", "url": "programmingfunda.com"}'

# parse x
y = json.loads(x)
print(y)

#get particular item from Dictionary
print(y['tutorial'])

Output


{'name': 'Programming', 'tutorial': 'Python', 'url': 'programmingfunda.com'}
Python

Python JSON dumps()

To convert Python Dictionary object to JSON, use json.dumps() method.

Example: Converting Python Object to JSON

import json

# Python Dictionary
x = {'name': 'Programming', 'tutorial': 'Python', 'url': 'programmingfunda.com'}

# convert into JSON
y = json.dumps(x)
print(y)

# Check type 
print(type(y))

Output


{"name": "Programming", "tutorial": "Python", "url": "programmingfunda.com"}
<class 'str'>

JSON Encoding and Decoding

  • Encoding: Converting Python objects (like lists, and dictionaries) into JSON.
  • Decoding: Converting JSON strings back into Python objects.

Encoding Example:

import json

data = {
    "name": "Alice",
    "age": 28,
    "is_employee": True,
    "skills": ["Python", "Data Science"]
}

# Convert Python dictionary to JSON string
json_string = json.dumps(data)
print(json_string)

Decoding Example:

json_data = '{"name": "Alice", "age": 28, "is_employee": true, "skills": ["Python", "Data Science"]}'

# Convert JSON string to Python dictionary
data = json.loads(json_data)
print(data)

Python json Module Functions

There are some functions provided by the JSON module which you can see below table.

Function NameDescription
json.dumps()Converts Python object to a JSON string.
json.dump()Writes a Python object as JSON to a file.
json.loads()Parses a JSON string and converts it into a Python object.
json.load()Reads JSON data from a file and returns a Python object.

Example: json.dump()

Saving Python object to JSON file.

import json

data = {
    "name": "Bob",
    "age": 25,
    "is_employee": False,
    "skills": ["Java", "C++"]
}

with open('data.json', 'w') as file:
    json.dump(data, file)

Example: json.load()

Loading JSON File into Python Object:

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

Examples and Use Cases

Here, I have mentioned some use cases of the Python JSON module along with examples.

1. Serializing and Deserializing Data for Web APIs

If you are working with REST APIs, you often need to send and receive JSON data.

Example: Sending Data in JSON Format:

import json
import requests

data = {
    "username": "john_doe",
    "password": "123456"
}

response = requests.post("https://example.com/api/login", json=data)

Note:- Replace the URL (https://example.com/api/login) with your original URL.

2. Storing Data in Files:

JSON is a popular format for storing configuration files or saving small amounts of data locally.

Example: Storing and Retrieving User Preferences:

import json

preferences = {
    "theme": "dark",
    "notifications": True,
    "volume": 80
}

# Saving preferences to file
with open('preferences.json', 'w') as f:
    json.dump(preferences, f)

# Loading preferences from file
with open('preferences.json', 'r') as f:
    preferences = json.load(f)
    print(preferences)

3. Reading JSON from Web:

Fetching data from a remote API that returns JSON and converting it to Python for processing.

Example: Fetching Data from an API:

import json
import requests

response = requests.get('https://api.github.com/users/octocat')
user_data = json.loads(response.text)
print(user_data)

Handling Errors

When working with JSON, it’s common to encounter malformed JSON strings. The json module provides helpful error-handling mechanisms.

Example: Handling Invalid JSON:

json_string = '{"name": "Alice", "age": "twenty"}'

try:
    data = json.loads(json_string)
except json.JSONDecodeError as e:
    print(f"Invalid JSON: {e}")

Additional Information

These Python objects can be converted into JSON using the Python JSON Module:-

dict
list
tuple
string
int
float
True
False
None

Example: Converting Python Objects to JSON

import json
print(json.dumps({"first_name": "Vishvajit", "last_name": "Rao"}))
print(json.dumps([1, 2, 3, 4, 5]))
print(json.dumps((1, 2, 3, 4, 5)))
print(json.dumps("Programming Funda"))
print(json.dumps(123))
print(json.dumps(12.90))
print(json.dumps(True))
print(json.dumps(False))
print(json.dumps(None))

Output

{"first_name": "Vishvajit", "last_name": "Rao"}
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
"Programming Funda"
123
12.9
true
false
null

When you are converted Python object to JSON, Python objects converted into JSON are equivalent:-

PythonJSON
dictObject
listArray
strString
intNumber
floatNumber
Nonenull
Falsefalse
Truetrue

Python Pretty Print JSON Object

Convert a Python object containing all the legal data types using json.dumps() function.

Example: Convert Python objects to JSON

import json
x = {

"name": "Programming Funda",
"age":10,
"type":"Online learning platform",
"course": "Programming Language",

"languages":[
{"database":"Mysql","markup":"HTML and CSS"},
{"Server":"PHP","Programming":"Python"}

]
}

#Check type before conversion
print(type(x))

y = json.dumps(x)
print(y)

#Check type after conversion
print(type(y))

Output

<class 'dict'>
{"name": "Programming Funda", "age": 10, "type": "Online learning platform", "course": "Programming Language", "languages": [{"database": "Mysql", "markup": "HTML and CSS"}, {"Server": "PHP", "Programming": "Python"}]}
<class 'str'>

The above example code will generate the above output which is not easy to read and does not follow the proper indentations. To make it properly readable use json.dumps() function.

The json.dumps() has parameters to make JSON string easy to read.

Example: Define the number of indents

Use the indent parameter to define the number of indents.

import json

x = {
"name": "Programming Funda",
"age":10,
"type":"Online learning platform",
"course": "Programming Language",

"languages":[
{"database":"Mysql","markup":"HTML and CSS"},
{"Server":"PHP","Programming":"Python"}

]
}
y = json.dumps(x, indent = 4)
print(y)

Output

{
    "name": "Programming Funda",
    "age": 10,
    "type": "Online learning platform",
    "course": "Programming Language",
    "languages": [
        {
            "database": "Mysql",
            "markup": "HTML and CSS"
        },
        {
            "Server": "PHP",
            "Programming": "Python"
        }
    ]
}

You can also define the separators, the default value is (“, “, “: “), which means using a comma and a space to separate each object, and a colon and a space to separate keys from values.

Example:

import json

x = {

"name": "Programming Funda",
"age":10,
"type":"Online learning platform",
"course": "Programming Language",

"languages":[
{"database":"Mysql","markup":"HTML and CSS"},
{"Server":"PHP","Programming":"Python"}

]
}
y = json.dumps(x, indent = 4, separators=(". ", " = "))
print(y)

Output

{
    "name" = "Programming Funda".
    "age" = 10.
    "type" = "Online learning platform".
    "course" = "Programming Language".
    "languages" = [
        {
            "database" = "Mysql".
            "markup" = "HTML and CSS"
        }.
        {
            "Server" = "PHP".
            "Programming" = "Python"
        }
    ]
}

Order the Result

The json.dumps() method has parameters to order the keys:

Example: Sorting the keys

Use the sort_keys parameter to specify if the result should be sorted or not.

import json
x = {

"name": "Programming Funda",
"age":10,
"type":"Online learning platform",
"course": "Programming Language",

"languages":[
{"database":"Mysql","markup":"HTML and CSS"},
{"Server":"PHP","Programming":"Python"}

]
}
y = json.dumps(x, indent = 4, sort_keys = True)
print(y)

Output

{
    "age": 10,
    "course": "Programming Language",
    "languages": [
        {
            "database": "Mysql",
            "markup": "HTML and CSS"
        },
        {
            "Programming": "Python",
            "Server": "PHP"
        }
    ],
    "name": "Programming Funda",
    "type": "Online learning platform"
}

Conclusion

The json module in Python is a powerful tool for converting Python objects to JSON and vice versa. It’s commonly used in web development, APIs, and data storage. Whether you’re sending data across networks or saving it in files, JSON makes data handling simple and efficient.

If you like this article, please share and keep visiting for further Python internals modules tutorials.

For more information about the Python JSON module:- Click Here

This article was written and verified by Vishvajit Rao.

Python String Module Complete Course

Related Posts