Python Create JSON

Python Create JSON

Python Create JSON

In Python, you can create JSON string by simply assigning a valid JSON string literal to a variable, or convert a Python Object to JSON string using json.loads() function.

In this tutorial, we will create JSON from different types of Python objects.

Example 1: Create JSON String from Python Dictionary

In this example, we will create JSON formatted string from a Python Dictionary. json.dumps() with indent argument returns a JSON formatted string value created from the dictionary.

Python Program

import json

dictionary = {'a':34, 'b':61, 'c':82}
jsonString = json.dumps(dictionary, indent=4)
print(jsonString)
Run this program ONLINE

Output

{
    "a": 34,
    "b": 61,
    "c": 82
}

Example 2: Create JSON String from Python List

In this example, we will create JSON formatted string from a Python List. Python List will have dictionaries as items.

Python Program

import json

myList = [{'a': 54}, {'b': 41, 'c':87}]
jsonString = json.dumps(myList, indent=4)
print(jsonString)
Run this program ONLINE

Output

[
    {
        "a": 54
    },
    {
        "b": 41,
        "c": 87
    }
]

Example 3: Create JSON String from Python Tuple

In this example, we will create JSON formatted string from a Python Tuple.

Python Program

import json

myTuple = ({'a': 54}, {'b': 41, 'c':87})
jsonString = json.dumps(myTuple, indent=4)
print(jsonString)
Run this program ONLINE

Output

[
    {
        "a": 54
    },
    {
        "b": 41,
        "c": 87
    }
]

Summary

In this tutorial of Python Examples, we learned how to create a JSON String from Python Objects, with the help of example programs.