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.

Examples

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 Code Copy

Output

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

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 Code Copy

Output

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

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 Code Copy

Output

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

Summary

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

Related Tutorials

Code copied to clipboard successfully 👍