Open In App

Convert Tuple to Json Array in Python

Last Updated : 09 Feb, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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 Python

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

Using json.dumps() method

In 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
import json
physics_tuple = ('Class 9', 'Physics', 'Laws of Motion', 'Introduction', 'Newton First Law')

# Convert tuple to JSON
json_data = json.dumps(physics_tuple)

# Display the result
print(type(json_data))
print(json_data)

Output
<class 'str'>
["Class 9", "Physics", "Laws of Motion", "Introduction", "Newton First Law"]

Making a Custom Encoder Function

In 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
import json
physics_tuple = ('Class 9', 'Physics', 'Laws of Motion', 'Introduction', 'Newton First Law')

def custom_encoder(obj):
    if isinstance(obj, tuple):
        return {'__tuple__': True, 'items': list(obj)}
    return obj

json_data = json.dumps(physics_tuple, default=custom_encoder)
print(type(json_data))
print(json_data)

Output
<class 'str'>
["Class 9", "Physics", "Laws of Motion", "Introduction", "Newton First Law"]

Using Pandas

In 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
import json
import pandas as pd

physics_tuple = ('Class 9', 'Physics', 'Laws of Motion',
                 ['Introduction', 'Newton First Law'])

df = pd.DataFrame([physics_tuple], columns=[
                  'Class', 'Subject', 'Topic', 'Subtopics'])
json_data = df.to_json(orient='records')

print(type(json_data))
print(json_data)

Output:

<class 'str'> 
[{"Class":"Class 9","Subject":"Physics","Topic":"Laws of Motion","Subtopics":["Introduction","Newton First Law"]}]

Custom Tuple serialization

In 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
import json

physics_tuple = ('Class 9', 'Physics', 'Laws of Motion', 'Introduction', 'Newton First Law')

def serialize(obj):
    if isinstance(obj, tuple):
        return {'tuple_items': list(obj)}
    return obj

json_data = json.dumps(physics_tuple, default=serialize)

print(type(json_data))
print(json_data)

Output
<class 'str'>
["Class 9", "Physics", "Laws of Motion", "Introduction", "Newton First Law"]

Practice Tags :

Similar Reads

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy