Borislav Hadzhiev
Last updated: Jul 2, 2022
Photo from Unsplash
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.
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.
Python | JSON |
---|---|
dict | object |
list, tuple | array |
str | string |
int, float, int and float derived Enums | number |
True | true |
False | false |
None | null |
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.
When you parse the JSON string into a native Python object, you get a list
back.
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.
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).