How to Convert Python Tuple to JSON Array?

Python – Convert Tuple to JSON Array

To convert Python Tuple to JSON Array, use json.dumps() method with the tuple passed as argument to the method.

In this tutorial, we shall learn how to create a JSON object from a tuple, with the help of example Python programs.

Syntax – json.dumps()

Following is the syntax of json.dumps() function.

jsonStr = json.dumps(mytuple)

Example 1: Convert Python Tuple to JSON String

In the following example, we have created a tuple and converted it to a JSON String. Python Tuple object converts to Array in JSON.

Python Program

import json

#python tuple
mytuple = ("python", "json", "mysql")

#convert to JSON string
jsonStr = json.dumps(mytuple)

#print json string
print(jsonStr)
Run this program

Output

["python", "json", "mysql"]

Example 2: Convert Python Tuple with Different Datatypes to JSON String

In the following example, we have created a tuple with values of different datatypes and converted it to a JSON String. Also, we will try to parse this JSON and access the elements.

Python Program

import json

#python tuple
mytuple = ("python", "json", 22, 23.04)

#convert to JSON string
jsonStr = json.dumps(mytuple)

#print json string
print(jsonStr)

#parse json
jsonArr = json.loads(jsonStr)

#print third item of the json array
print(jsonArr[2])
Run this program

Output

["python", "json", 22, 23.04]
22

Summary

In this tutorial of Python Examples, we learned how to convert a Python Tuple to a JSON String.