Open In App

Convert List Of Tuples To Json Python

Last Updated : 01 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Working with data often involves converting between different formats, and JSON is a popular choice for data interchange due to its simplicity and readability. In Python, converting a list of tuples to JSON can be achieved through various approaches. In this article, we’ll explore four different methods, each offering its own advantages in different scenarios.

Convert List Of Tuples To Json in Python

Below are some of the ways by which we can convert a list of tuples to JSON in Python:

Convert List Of Tuples to Json Using json.dumps()

In this example, the json.dumps() function is employed to convert a list of tuples (list_of_tuples) into a JSON-formatted string (json_data). This approach is straightforward and suitable for simple data structures.

Python3




import json
 
list_of_tuples = [(1, 'apple'), (2, 'banana'), (3, 'cherry')]
 
json_data = json.dumps(list_of_tuples)
 
print(json_data)
print(type(json_data))


Output

[[1, "apple"], [2, "banana"], [3, "cherry"]]
<class 'str'>

Python Convert List Of Tuples to Json Using List Comprehension

In this example, list comprehension is utilized to transform each tuple in the list_of_tuples into a dictionary with meaningful keys (id and fruit). The resulting list of dictionaries is then converted to JSON, providing more control over the JSON structure.

Python3




import json
 
list_of_tuples = [(1, 'apple'), (2, 'banana'), (3, 'cherry')]
 
list_of_dicts = [{'id': item[0], 'fruit': item[1]} for item in list_of_tuples]
 
json_data = json.dumps(list_of_dicts)
 
print(json_data)
print(type(json_data))


Output

[{"id": 1, "fruit": "apple"}, {"id": 2, "fruit": "banana"}, {"id": 3, "fruit": "cherry"}]
<class 'str'>

Convert List Of Tuples to Json Using json.JSONEncoder

In this example, a custom JSON encoder (TupleEncoder) is created by subclassing json.JSONEncoder. The encoder is designed to handle the encoding of tuples into a custom format. This approach allows for a more personalized and extensible solution.

Python3




import json
 
class TupleEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, tuple):
            return {'type': 'tuple', 'value': list(obj)}
        return super().default(obj)
 
list_of_tuples = [(1, 'apple'), (2, 'banana'), (3, 'cherry')]
 
json_data = json.dumps(list_of_tuples, cls=TupleEncoder)
 
print(json_data)
print(type(json_data))


Output

[[1, "apple"], [2, "banana"], [3, "cherry"]]
<class 'str'>

Python Convert List Of Tuples To Json Using Pandas Library

In this example, the Pandas library is leveraged to convert a list of tuples (list_of_tuples) into a Pandas DataFrame (df). The to_json() method of the DataFrame is then used to generate JSON data in the specified orientation (‘records’). This approach is beneficial when working with more complex data structures or when Pandas is already part of the project.

Python3




import pandas as pd
 
list_of_tuples = [(1, 'apple'), (2, 'banana'), (3, 'cherry')]
 
df = pd.DataFrame(list_of_tuples, columns=['id', 'fruit'])
 
json_data = df.to_json(orient='records')
 
print(json_data)
print(type(json_data))


Output:

[{"id":1,"fruit":"apple"},{"id":2,"fruit":"banana"},{"id":3,"fruit":"cherry"}]



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads