Getting Started

Python - IntroductionPython - Hello World ProgramPython - SyntaxPython - Data TypesPython - Variables

Operators

Python - Arithmetic OperatorsPython - Relational OperatorsPython - Logical OperatorsPython - Assignment OperatorsPython - Bitwise OperatorsPython - Membership OperatorsPython - Identity OperatorsPython - Increment and Decrement Operators

Conditions

Python - If Else statement

Loop

Python - While LoopPython - For Loop

Numbers

Python - NumbersPython - Number Conversion

Strings

Python - StringsPython - String OperatorsPython - String FormattingPython - String MethodsPython - String Format Method

List

Python - ListPython - List Methods

Tuple

Python - Tuple

Set

Python - SetPython - Set Methods

Dictionary

Python - DictionaryPython - Dictionary Methods

Functions

Python - FunctionsPython - Functions - Variable length argumentsPython - Lambda Function

Scope of Variables

Python - Scope of Variables

Modules

Python - ModulesPython - Math ModulePython - JSON ModulePython - datetime ModulePython - time Module

I/O

Python - Read input from keyboard

File

Python - File Handling

Exception Handling

Python - Exception Handling

OOP

Python - Classes and ObjectsPython - Class Constructor __init__ methodPython - Class Destructor __del__ methodPython - Built-in Class AttributesPython - InheritancePython - Method OverridingPython - Method Overloading

Package Management

Python - PIP

Python - MySQL

Python - MySQL - Getting StartedPython - MySQL - Insert dataPython - MySQL - Select dataPython - MySQL - Update dataPython - MySQL - Delete data

Python - CSV

Python - Read data from CSV filePython - Write data in CSV file

Python - JSON Module

Python

python logo

In this tutorial we will learn to work with JSON in Python.

What is a JSON?

JSON or JavaScript Object Notation is a lightweight format for storing and exchanging data.

Sample:

{
  "username": "yusufshakeel",
  "score": 9.1,
  "isOnline": false
}

The json module

To work with JSON in Python we have to import the json module.

import json

The json.dumps() method

To convert Python object into JSON we use the json.dumps() method from the json module.

In the following Python program we are converting a Python dictionary into a JSON string.

# import module
import json

# dict
userData = {
  "username": "yusufshakeel",
  "score": 9.1,
  "isOnline": False
}

# convert to JSON
userData_JSON = json.dumps(userData)

# output
print("Type of userData:", type(userData))
print("Type of userData_JSON:", type(userData_JSON))

print("userData:", userData)
print("userData_JSON:", userData_JSON)

The above code will give us the following output.

Type of userData: <class 'dict'>
Type of userData_JSON: <class 'str'>
userData: {'username': 'yusufshakeel', 'score': 9.1, 'isOnline': False}
userData_JSON: {"username": "yusufshakeel", "score": 9.1, "isOnline": false}

To make the JSON string more readable we can pass indent argument to the json.dumps() method.

In the following Python program we are coverting a Python object to JSON string using the json.dumps() method and passing indent=2 to make the string more readable.

# import module
import json

# dict
userData = {
  "username": "yusufshakeel",
  "score": 9.1,
  "isOnline": False
}

# convert to JSON
userData_JSON = json.dumps(userData, indent=2)

# output
print("Type of userData:", type(userData))
print("Type of userData_JSON:", type(userData_JSON))

print("userData:", userData)
print("userData_JSON:", userData_JSON)

We will get the following output.

Type of userData: <class 'dict'>
Type of userData_JSON: <class 'str'>
userData: {'username': 'yusufshakeel', 'score': 9.1, 'isOnline': False}
userData_JSON: {
  "username": "yusufshakeel",
  "score": 9.1,
  "isOnline": false
}

Python object to JSON

We can convert the following Python objects into JSON using the json.dumps() method.

Python ObjectJSON
Truetrue
Falsefalse
intNumber
floatNumber
strString
listArray
tupleArray
dictObject
Nonenull

In the following Python program we are coverting Python object into JSON string.

# import module
import json

# data
data = {
    "int": 1,
    "float": 3.14,
    "string": "yusufshakeel",
    "list": [1, 2, 3],
    "tuple": (1, 2, 3),
    "dict": { "x": 10, "y": 20 },
    "boolTrue": True,
    "boolFalse": False,
    "noneVal": None
}

# convert to JSON
data_JSON = json.dumps(data)

# output
print("Type of data:", type(data))
print("Type of data_JSON:", type(data_JSON))

print("data:", data)
print("data_JSON:", data_JSON)

The above Python code will give us the following output.

Type of data: <class 'dict'>
Type of data_JSON: <class 'str'>
data: {'int': 1, 'float': 3.14, 'string': 'yusufshakeel', 'list': [1, 2, 3], 'tuple': (1, 2, 3), 'dict': {'x': 10, 'y': 20}, 'boolTrue': True, 'boolFalse': False, 'noneVal': None}
data_JSON: {
  "int": 1,
  "float": 3.14,
  "string": "yusufshakeel",
  "list": [
    1,
    2,
    3
  ],
  "tuple": [
    1,
    2,
    3
  ],
  "dict": {
    "x": 10,
    "y": 20
  },
  "boolTrue": true,
  "boolFalse": false,
  "noneVal": null
}

The json.loads() method

We use the json.loads() method to convert JSON string into Python object.

In the following Python program we are converting a JSON string into a Python object.

# import module
import json

# json
data_JSON = '{"username": "yusufshakeel", "score": 9.1, "isOnline": false}'

# covert
data = json.loads(data_JSON)

# output
print("Type of data_JSON:", type(data_JSON))
print("Type of data:", type(data))

print("data_JSON:", data_JSON)
print("data:", data)

The above code will give use the following output.

Type of data_JSON: <class 'str'>
Type of data: <class 'dict'>
data_JSON: {"username": "yusufshakeel", "score": 9.1, "isOnline": false}
data: {'username': 'yusufshakeel', 'score': 9.1, 'isOnline': False}