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 of json.dumps()

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

jsonStr = json.dumps(mytuple)

Examples

1. Convert a tuple of strings 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 Code Copy

Output

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

2. Convert a 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 Code Copy

Output

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

Summary

In this Python JSON Tutorial, we learned how to convert a Python Tuple to a JSON String.

Related Tutorials

Code copied to clipboard successfully 👍