Horje
Convert Python List to Json

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'>





Reffered: https://www.geeksforgeeks.org


Python

Related
Load H5 Files In Python Load H5 Files In Python
How to append new data to existing XML using Python ElementTree How to append new data to existing XML using Python ElementTree
Python Super() With __Init__() Method Python Super() With __Init__() Method
Convert Dictionary to DataFrame in Python with column names Convert Dictionary to DataFrame in Python with column names
Extract Multiple JSON Objects from one File using Python Extract Multiple JSON Objects from one File using Python

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
13