How to convert a Tuple to JSON in Python

avatar

Borislav Hadzhiev

Last updated: Jul 2, 2022

banner

Photo from Unsplash

Convert a Tuple to JSON in Python #

Use the json.dumps() method to convert a tuple to JSON, e.g. json_str = json.dumps(my_tuple). The json.dumps() method converts a Python object to a JSON formatted strings and supports tuple to JSON array conversion.

main.py
import json my_tuple = ('one', 'two', 'three') json_str = json.dumps(my_tuple) print(json_str) # 👉️ '["one", "two", "three"]' print(type(json_str)) # 👉️ <class 'str'>

We used the json.dumps method to convert a tuple to a JSON string.

The json.dumps method converts a Python object to a JSON formatted string.

Python tuples are JSON serializable, just like lists or dictionaries.

The JSONEncoder class supports the following objects and types by default.

PythonJSON
dictobject
list, tuplearray
strstring
int, float, int and float derived Enumsnumber
Truetrue
Falsefalse
Nonenull

The process of converting a tuple (or any other native Python object) to a JSON string is called serialization.

Whereas, the process of converting a JSON string to a native Python object is called deserialization.

It should be noted that Python tuples get converted to a JSON array, just like lists.

When you parse the JSON string into a native Python object, you get a list back.

main.py
import json my_tuple = ('one', 'two', 'three') # 👇️ convert tuple to JSON json_str = json.dumps(my_tuple) print(json_str) # 👉️ '["one", "two", "three"]' print(type(json_str)) # 👉️ <class 'str'> # -------------------------------- # 👇️ parse JSON string to native Python object parsed = json.loads(json_str) print(parsed) # 👉️ ['one', 'two', 'three'] print(type(parsed)) # 👉️ <class 'list'>

Notice that we got a list object after parsing the JSON string. This is because both list and tuple objects get converted to a JSON array when serialized.

You can use the tuple() class to convert the list to a tuple after parsing the JSON string.

main.py
import json my_tuple = ('one', 'two', 'three') json_str = json.dumps(my_tuple) print(json_str) # 👉️ '["one", "two", "three"]' print(type(json_str)) # 👉️ <class 'str'> # -------------------------------- # 👇️ convert to tuple parsed = tuple(json.loads(json_str)) print(parsed) # 👉️ ('one', 'two', 'three') print(type(parsed)) # 👉️ <class 'tuple'>

The example uses the tuple() class to convert the list we got after parsing the JSON string.

Tuples are very similar to lists, but implement fewer built-in methods and are immutable (cannot be changed).

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.