
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Dump 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.
Its 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 use 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.
Json.dumps()
The dumps() method is used to convert the Python object to a JSON string. Not all objects are convertible, and we need to create a dictionary of data we wish to expose before serializing to JSON. For example, class.
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, 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
Following is an output of the above code -
[10, "python", true, 20, 30]
Example
Let's see another example to understand the process of dumping 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
Following is an output of the above code -
[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 JSON format. The JSON output is in the string format, and the elements are printed on a new line as we enabled the indent parameter as True.
[ true, 10, 30, "python" ] The type of the json format: <class 'str'>