Open In App

Convert Python List to Json

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

JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy for humans to read and write, and easy for machines to parse and generate. In Python, the json module provides a convenient way to work with JSON data. In this article, we’ll explore how to convert Python lists to JSON, along with some examples.

Convert List to JSON in Python

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

  1. Using json.dumps() method
  2. Using json.dump() method
  3. Using json.JSONEncoder

Using json.dumps() Method

In this example, a Python list containing a mix of integers and strings (list_1) is converted to a JSON-formatted string (json_str) using json.dumps(). The resulting JSON string maintains the original list’s structure, allowing for interoperability with other systems or storage.

Python3




import json
 
# list of integer & string
list_1 = [1, 2, 3, "four", "five"]
print(type(list_1))
print("Real List:", list_1)
 
# convert to Json
json_str = json.dumps(list_1)
# displaying
print(type(json_str))
print("Json List:", json_str)


Output

<class 'list'>
Real List: [1, 2, 3, 'four', 'five']
<class 'str'>
Json List: [1, 2, 3, "four", "five"]


Using json.dump() Method

In this example, a list of lists (data) is converted into a JSON-formatted file named “mydata.json” using the json.dump() function. Subsequently, the file is downloaded from the Colab environment using files.download(), providing a convenient way to retrieve and use the generated JSON file.

Python3




import json
from google.colab import files
 
# List of lists
data = [
    ["1", "2", "3"],
    ["4", "5", "6"],
    ["7", "8", "9"]
]
 
# Convert into JSON
# File name is mydata.json
with open("mydata.json", "w") as final:
    json.dump(data, final)
 
# Download the file
files.download('mydata.json')


mydata.json

[["1", "2", "3"], ["4", "5", "6"], ["7", "8", "9"]]

Using json.JSONEncoder

In the following example, the Python json module is used to customize the serialization of a list of Lists. Here, we are converting Python list of lists to json. The ‘json.JSONEncoder‘ class is subclassed, which is overriding the default method. It will convert the list of lists ‘data’ during the process of JSON encoding, that results in a formatted JSON string with indents for improved readability.

Python3




import json
 
class ListOfListsEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, list):
            return obj
        return json.JSONEncoder.default(self, obj)
 
# List of lists
data = [
    ["1", "2", "3"],
    ["4", "5", "6"],
    ["7", "8", "9"]
]
 
print(type(data))
# Convert into JSON using custom encoder
json_output = json.dumps(data, cls=ListOfListsEncoder)
 
print(json_output)
print(type(json_output))


Output

<class 'list'>
[["1", "2", "3"], ["4", "5", "6"], ["7", "8", "9"]]
<class 'str'>




Previous Article
Next Article

Similar Reads

Python - Difference between json.dump() and json.dumps()
JSON is a lightweight data format for data interchange which can be easily read and written by humans, easily parsed and generated by machines. It is a complete language-independent text format. To work with JSON data, Python has a built-in package called json. Note: For more information, refer to Working With JSON Data in Python json.dumps() json.
2 min read
Python - Difference Between json.load() and json.loads()
JSON (JavaScript Object Notation) is a script (executable) file which is made of text in a programming language, is used to store and transfer the data. It is a language-independent format and is very easy to understand since it is self-describing in nature. Python has a built-in package called json. In this article, we are going to see Json.load a
3 min read
Python - Convert list of dictionaries to JSON
In this article, we will discuss how to convert a list of dictionaries to JSON in Python. Python Convert List of Dictionaries to JsonBelow are the ways by which we can convert a list of dictionaries to JSON in Python: Using json.dumps()Using json.dump()Using json.JSONEncoderUsing default ParameterDictionaries to JSON in Python Using json.dumps()In
5 min read
Convert List Of Tuples To Json Python
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 differen
3 min read
Convert List Of Tuples To Json String in Python
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 PythonBelow, are the methods of Convert List Of Tuples To Json String In Python: Using map() FunctionUsing dict() C
3 min read
Python | Ways to convert string to json object
In this article, we will see different ways to convert string to JSON in Python this process is called serialization. JSON module provides functions for encoding (serializing) Python objects into JSON strings and decoding (deserializing) JSON strings into Python objects. Encoding (Serializing) JSON: If you have a Python object and want to convert i
3 min read
Convert JSON to dictionary in Python
JSON stands for JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called JSON. To use this feature, we import the Python JSON package into Python script. The text in JSON is done through quoted-
3 min read
Convert JSON to CSV in Python
The full form of JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called JSON. To use this feature, we import the JSON package in Python script. The text in JSON is done through quoted-
3 min read
Convert Text file to JSON in Python
JSON (JavaScript Object Notation) is a data-interchange format that is human-readable text and is used to transmit data, especially between web applications and servers. The JSON files will be like nested dictionaries in Python. To convert a text file into JSON, there is a json module in Python. This module comes in-built with Python standard modul
4 min read
Python - Convert JSON to string
Data in transmitted across platforms using API calls. Data is mostly retrieved in JSON format. We can convert the obtained JSON data into String data for the ease of storing and working with it. Let's see how to convert JSON to String. Method #1: Json to String on dummy data using "json.dumps" C/C++ Code import json # create a sample json a = {
1 min read
Practice Tags :