Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Convert List of Tuples to List of Strings - Python
Next article icon

Convert List Of Tuples To Json String in Python

Last Updated : 01 Mar, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

We have a list of tuples and our task is to convert the list of tuples into a JSON string in Python. In this article, we will see how we can convert a list of tuples to a JSON string in Python.

Convert List Of Tuples To Json String in Python

Below, are the methods of Convert List Of Tuples To Json String In Python:

  • Using map() Function
  • Using dict() Constructor
  • Using str() Method

Convert List Of Tuples To Json String Using map() Function

In this example, below Python code below converts a list of tuples into a JSON string using the `JSON` module. It employs a mapping function to transform each tuple into a dictionary, then uses `map` and `below n.dumps` for the conversion. The resulting JSON string is printed.

Python3
import json  # Sample list of tuples list_of_tuples = [(1, 'apple'), (2, 'banana'), (3, 'cherry')]  # Define a mapping function def tuple_to_dict(tpl):     return {tpl[0]: tpl[1]}  # Convert to JSON string using map and dumps json_string = json.dumps(list(map(tuple_to_dict, list_of_tuples)))  print(type(list_of_tuples))  # Display the result print(json_string)  print(type(json_string)) 

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

Convert List Of Tuples To Json String Using dict() Constructor

In this example, below Python code uses the `json` module to convert a list of tuples into a JSON string. It first transforms the list into a dictionary and then utilizes `json.dumps()` to generate the JSON string. The final result is printed, demonstrating a concise way to handle such conversions.

Python3
import json  # Sample list of tuples list_of_tuples = [(1, 'apple'), (2, 'banana'), (3, 'orange')]  # Convert the list of tuples to a dictionary dictionary_data = dict(list_of_tuples)  # Convert the dictionary to a JSON string json_string = json.dumps(dictionary_data)  print(type(list_of_tuples)) print(type(json_string))  # Display the result print(json_string) 

Output
<class 'list'> <class 'str'> {"1": "apple", "2": "banana", "3": "orange"} 

Convert List Of Tuples To Json String Using Non-String Keys and Values

In this approach, a list of tuples with mixed data types is converted into a dictionary. To ensure compatibility with JSON, both keys and values are explicitly converted to strings before creating the dictionary. The resulting dictionary is then converted to a JSON string using json.dumps().

Python3
import json  # Another sample list of tuples with mixed data types list_of_tuples = [('a', 1), (2, 'b'), ('c', True)]  # Convert the list of tuples to a dictionary, ensuring both keys and values are strings mixed_dictionary_data = {str(key): str(value) for key, value in list_of_tuples}  # Convert the dictionary to a JSON string json_string = json.dumps(mixed_dictionary_data)  print(type(list_of_tuples)) print(type(json_string))  # Display the result print(json_string) 

Output
<class 'list'> <class 'str'> {"a": "1", "2": "b", "c": "True"} 

Conclusion

In conlcusion, Converting a list of tuples to a JSON string in Python can be achieved through various methods, each offering flexibility based on your specific requirements. Whether you prefer the simplicity of the json module or the more explicit approaches involving list comprehensions or the map function, understanding these methods provides you with the tools to efficiently work with JSON data in your Python applications.


Next Article
Convert List of Tuples to List of Strings - Python

G

gargjyotgvwt
Improve
Article Tags :
  • Python
  • Python Programs
  • python-tuple
  • Python-json
Practice Tags :
  • python

Similar Reads

  • Python | Convert String to list of tuples
    Sometimes, while working with data, we can have a problem in which we have a string list of data and we need to convert the same to list of records. This kind of problem can come when we deal with a lot of string data. Let's discuss certain ways in which this task can be performed. Method #1: Using
    8 min read
  • Convert list of strings to list of tuples in Python
    Sometimes we deal with different types of data types and we require to inter-convert from one data type to another hence interconversion is always a useful tool to have knowledge. This article deals with the converse case. Let's discuss certain ways in which this can be done in Python. Method 1: Con
    5 min read
  • Convert List of Tuples to List of Strings - Python
    The task is to convert a list of tuples where each tuple contains individual characters, into a list of strings by concatenating the characters in each tuple. This involves taking each tuple, joining its elements into a single string, and creating a new list containing these strings. For example, gi
    3 min read
  • Python | Convert String to tuple list
    Sometimes, while working with Python strings, we can have a problem in which we receive a tuple, list in the comma-separated string format, and have to convert to the tuple list. Let's discuss certain ways in which this task can be performed. Method #1 : Using loop + split() + replace() This is a br
    5 min read
  • Convert tuple to string in Python
    The goal is to convert the elements of a tuple into a single string, with each element joined by a specific separator, such as a space or no separator at all. For example, in the tuple ('Learn', 'Python', 'Programming'), we aim to convert it into the string "Learn Python Programming". Let's explore
    3 min read
  • Convert Set of Tuples to a List of Lists in Python
    Sets and lists are two basic data structures in programming that have distinct uses. It is sometimes necessary to transform a collection of tuples into a list of lists. Each tuple is converted into a list throughout this procedure, and these lists are subsequently compiled into a single, bigger list
    3 min read
  • Convert Dictionary to List of Tuples - Python
    Converting a dictionary into a list of tuples involves transforming each key-value pair into a tuple, where the key is the first element and the corresponding value is the second. For example, given a dictionary d = {'a': 1, 'b': 2, 'c': 3}, the expected output after conversion is [('a', 1), ('b', 2
    3 min read
  • Python | Convert string tuples to list tuples
    Sometimes, while working with Python we can have a problem in which we have a list of records in form of tuples in stringified form and we desire to convert them to a list of tuples. This kind of problem can have its occurrence in the data science domain. Let's discuss certain ways in which this tas
    4 min read
  • Python | List of tuples to String
    Many times we can have a problem in which we need to perform interconversion between strings and in those cases, we can have a problem in which we need to convert a tuple list to raw, comma separated string. Let's discuss certain ways in which this task can be performed. Method #1: Using str() + str
    8 min read
  • Python | Convert list of tuples into list
    In Python we often need to convert a list of tuples into a flat list, especially when we work with datasets or nested structures. In this article, we will explore various methods to Convert a list of tuples into a list. Using itertools.chain() itertools.chain() is the most efficient way to flatten a
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences