Python - Convert 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)
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])
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.