AppDividend
Latest Code Tutorials

How to Convert Python Tuple to JSON

0

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 an Encoding. To work with JSON objects, you can use Python’s json module. 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(). JSON Library of Python 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

Convert Python Tuple to JSON

To convert Python Tuple to JSON, use the json.dumps() method and pass the tuple as an argument to the method. The json.dumps() method converts a Python 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.

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 object tutorial.

See also

Python tuple to set

Python tuple to string

Python tuple to array

Python tuple to dictionary

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.