To convert a List of Tuples to a JSON string in Python:
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.
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"}.
0 Comments