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 |
Python Tuple to JSON
To convert Python tuple to JSON, use the json.dumps() method. The json.dumps() method accepts the tuple to convert an object into a json string. To work with json related functions, import json module at the head of the Python file.
import json tup = ("Dhirubhai", "Ratan", "Timothee") jsonObj = json.dumps(tup) print(jsonObj)
Output
["Dhirubhai", "Ratan", "Timothee"]
We got the json string in the output.
Convert Python 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. To read a file containing JSON object, use the json.load() method. That is it for converting Python tuple to json string tutorial.