To convert a tuple to JSON in Python, you can use the json.dumps() method. The json.dumps() method accepts the tuple to convert an object into a json string.
import json
tup = ("Dhirubhai", "Ratan", "Timothee")
jsonObj = json.dumps(tup)
print(jsonObj)
Output
["Dhirubhai", "Ratan", "Timothee"]
We got the json string in the output.
The JSON library in Python is used for data serialization. JSON stands for Javascript object notation. The operation of converting Python Object to JSON is called Encoding.
To work with JSON objects, you can use Python’s json module. However, you need to import the module before you can use it.
The encoding is done with the help of the JSON library method json.dumps(). Python’s JSON Library delivers the following conversion of Python objects into JSON objects by default.
Python | JSON |
dict | Object |
tuple | Array |
list | Array |
Unicode | String |
number – int, long | number – int |
float | number – real |
True | True |
False | False |
None | Null |
Converting Tuple with Different Datatypes to JSON String
If you have a Python tuple with different data types, you can convert it into a JSON string using the json.dumps() method.
import json
tup = ("Dhirubhai", 72, True, 5.8)
jsonObj = json.dumps(tup)
print(jsonObj)
print(type(jsonObj))
Output
["Dhirubhai", 72, true, 5.8]
<class 'str'>
In this example, we have created a tuple with values of different data types like String, Integer, Boolean, and Float and converted it to a JSON String.
We can parse this JSON and access the elements using json.loads() method.
import json
tup = ("Dhirubhai", 72, True, 5.8)
jsonObj = json.dumps(tup)
print(jsonObj)
print(type(jsonObj))
print("Converting JSON to List")
jsonArr = json.loads(jsonObj)
print(jsonArr[1])
print(type(jsonArr))
Output
["Dhirubhai", 72, true, 5.8]
<class 'str'>
Converting JSON to List
72
<class 'list'>
The json module makes it easy to parse JSON strings and files containing JSON objects. The json.loads() method converts the JSON string into a list.
That’s it.