How I can dump a Python tuple in JSON format?


JSON can be abbreviated as JavaScript Object Notation. It means a script of a text file in a programming language to transfer and store the data. It is supported by the python programming language using a built-in package named json.

It’s text is given in the quoted string format which contains a key and value within the curly braces{} which looks like a dictionary.

To access a JSON document using python we have to import the json package. In this package we have a method named dumps() which is used to convert the python tuple objects into the Java objects.

Syntax

The following is the syntax of the dumps method of the json package.

variable_name = json.dumps(tuple)

Example

When we pass the tuple to the dumps() function, then the tuple data will be dumped into JSON format. The following is the code.

import json
tuple = (10,'python',True,20,30)
json = json.dumps(tuple)
print(json)

Output

[10, "python", true, 20, 30]

Example

Let’s see another example to understand the process to dump the python tuple into the Json format.

import json
tuple = (12, "Ravi", "B.Com FY", 78.50)
json = json.dumps(tuple)
print(json)
print("The type of the json format:",type(json))

Output

[12, "Ravi", "B.Com FY", 78.5]
The type of the json format: <class 'str'>

Example

If we want to retrieve the JSON document along with the spaces we need to call the dumps() method by setting the optional parameter indent to True.

import json
tuple = (True,10,30,'python')
json = json.dumps(tuple, indent = True)
print(json)
print("The type of the json format:",type(json))

Output

The following is the output of the json package dumps method. In the output we can see the converted JSON format and the type of the json format. The json output is in the string format and the elements are printed in new line as we enabled the indent parameter as True.

[
 true,
 10,
 30,
 "python"
]
The type of the json format: <class 'str'>

Updated on: 15-May-2023

644 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements