![]() |
Python’s versatility as a programming language extends to its rich data structures, including tuples and JSON. JSON, abbreviation for JavaScript Object Notation, is a lightweight data format used for representing structured data. Moreover, it is a syntax for storing and exchanging data. In this article, we will see how to write a tuple to JSON in Python. Converting Tuple to JSON in PythonBelow are some of the ways by which we can convert Tuple to JSON in Python: Using json.dumps() methodIn this example, the `json.dumps()` function is used to convert a tuple named `physics_tuple` into a JSON-formatted string (`json_data`). The resulting JSON string is then displayed along with its data type, showcasing the serialization of the tuple into a JSON representation. Python3
Output
<class 'str'> ["Class 9", "Physics", "Laws of Motion", "Introduction", "Newton First Law"] Making a Custom Encoder FunctionIn this example, a custom JSON encoder function named `custom_encoder` is defined to handle the serialization of tuples. The function converts tuples into a dictionary format with a special key `__tuple__` and a list of items. This custom encoder is then utilized with the `json.dumps` function using the `default` parameter. The resulting JSON string, representing the serialized tuple, is displayed along with its data type. Python3
Output
<class 'str'> ["Class 9", "Physics", "Laws of Motion", "Introduction", "Newton First Law"] Using PandasIn this example, a tuple named `physics_tuple` is converted into a Pandas DataFrame (`df`) with specific column names. The fourth element of the tuple is a list, which is included as a column named ‘Subtopics’ in the DataFrame. The `to_json` method is then applied to the DataFrame with the specified orientation (‘records’), resulting in a JSON-formatted string (`json_data`) representing the data in a record-oriented format suitable for a list of dictionaries. Python3
Output: <class 'str'> Custom Tuple serializationIn this example, a custom serialization function named `serialize` is defined to handle the serialization of tuples. The function converts tuples into a dictionary format with a key ‘tuple_items’ containing a list of items. This custom serialization function is then utilized with the `json.dumps()` function using the `default` parameter. The resulting JSON string, representing the serialized tuple, is displayed along with its data type. Python3
Output
<class 'str'> ["Class 9", "Physics", "Laws of Motion", "Introduction", "Newton First Law"] |
Reffered: https://www.geeksforgeeks.org
Python |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 14 |