To convert a tuple to JSON(Javascript object notation.) in Python, you can use the json.dumps() method.
The json.dumps() method serializes objects (like tuples) into a JSON formatted string.
Here’s a table that outlines the default conversions performed by JSON module:
Python | JSON |
dict | Object |
tuple | Array |
list | Array |
str | String |
number – int, long | number – int |
float | number – real |
True | true |
False | false |
None | null |
Example 1: Tuple of Strings
Visual Representation
import json
# Define a tuple
my_tuple = ("Apple", "Meta", "Tesla")
print(my_tuple)
print(type(my_tuple))
# Convert the tuple to JSON
json_data = json.dumps(my_tuple)
print(json_data)
print(type(json_data))
Output
('Apple', 'Meta', 'Tesla')
<class 'tuple'>
["Apple", "Meta", "Tesla"]
<class 'str'>
Example 2: Using Different Datatypes
Visual Representation
import json
# Define a tuple
my_tuple = ("Apple", 4, 2.34, True)
print(my_tuple)
print(type(my_tuple))
json_data = json.dumps(my_tuple)
print(json_data)
print(type(json_data))
Output
('Apple', 4, 2.34, True)
<class 'tuple'>
["Apple", 4, 2.34, true]
<class 'str'>