![]() |
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 PythonBelow 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
Output
[[1, "apple"], [2, "banana"], [3, "cherry"]] <class 'str'> Python Convert List Of Tuples to Json Using List ComprehensionIn 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
Output
[{"id": 1, "fruit": "apple"}, {"id": 2, "fruit": "banana"}, {"id": 3, "fruit": "cherry"}] <class 'str'> Convert List Of Tuples to Json Using json.JSONEncoderIn 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
Output
[[1, "apple"], [2, "banana"], [3, "cherry"]] <class 'str'> Python Convert List Of Tuples To Json Using Pandas LibraryIn 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
Output: [{"id":1,"fruit":"apple"},{"id":2,"fruit":"banana"},{"id":3,"fruit":"cherry"}] |
Reffered: https://www.geeksforgeeks.org
Geeks Premier League |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 13 |