python

Convert List of Tuples to JSON string in Python

You can use the json module in Python to convert a list of tuples to a JSON string. We will explain it with examples in this post.

Convert List of Tuples to JSON string in Python

To convert a List of Tuples to a JSON string in Python:

  1. Create a List of Tuples - my_data = [("data1", "value1"), ("data2", "value2")].
  2. Import json module and use json.dumps() to convert it - json.dumps(my_data).

Here is an example:

import json

list_of_tuples = [("John", "New York"), ("Tina", "Germany")]

result = json.dumps(list_of_tuples)

print(result)

Output

[["John", "New York"], ["Tina", "Germany"]]

The json.dumps() function takes a Python object (in this case, a list of tuples) and converts it to a JSON-formatted string. The resulting JSON string can be saved to a file, sent over a network, or used in any other way than you would use a string.

Note that the json.dumps() method will only work if the elements in the tuple is serializable.

You can also convert the List of Tuples to the dictionary first and then generate the JSON string to make it in Object format. But you can only have two items in each tuple of the List to make it work.

import json

list_of_tuples = [("John", "New York"), ("Tina", "Germany")]

result = json.dumps(dict(list_of_tuples))

print(result)

Output

{"John": "New York", "Tina": "Germany"}

This code takes a list of tuples, converts it to a dictionary using the dict() method, and then converts the dictionary to a JSON string using the json.dumps() method. Finally, the JSON string is printed out. The output of this code would be: {"John":"New York","Tina":"Germany"}.


Was this helpful?