How to Convert Python List to JSON

Introduction

The json library provides functions and methods to parse JSON from strings and files.

The json library supports functions that can convert dictionaries and lists to JSON strings.

Every one of the data structures present in Python offers something unique to the table. For example, working with APIs involves the manipulation of JSON data.

Let’s see how to convert a list to JSON format.

How to convert a List to JSON in Python

There is a built-in function called json.dumps() that converts a list to json in Python. The json.dumps() method takes a list as an argument and returns the json value.

The json.dumps() function can convert data types such as a dictionary, string, integer, float, boolean, and None into JSON.

To work with json in your project, import the json package into your file using the import statement.

After that, you can use the json module anywhere in your program.

# app.py

import json

data = ["DisneyPlus", "Netflix", "Peacock"]
json_string = json.dumps(data)
print(json_string)

Output

➜  pyt python3 app.py
["DisneyPlus", "Netflix", "Peacock"]
➜  pyt

You can see that we converted json string to a list using the dumps() method.

How to Convert a List of Dictionaries to JSON

Use the json.dumps() method to convert a list of dictionaries to json in Python.

import json

list_of_dicts = [{'kb':19, 'kl':21}, {'mbb':11, 'sm':18}]
json_str = json.dumps(list_of_dicts)
print(json_str)

Output

[{"kb": 19, "kl": 21}, {"mbb": 11, "sm": 18}]

You can see that we converted a list of dictionaries to json string without losing any original data.

How to Convert a List of Lists to JSON

The json.dumps() method converts a list of lists to json string in Python. It accepts the list of lists as an argument and returns the json string without losing any input data.

import json

list_of_lists = [[19, 21], [11, 18], [46]]
json_str = json.dumps(list_of_lists)
print(json_str)

Output

[[19, 21], [11, 18], [46]]

How to Write JSON data to a file in Python

To write a json data into a file, use the with open() function in the “w” mode and then use the json.dump() method to write all the content in the file.

Let’s implement a program to write the JSON data into a file.

# app.py

import json

data = {"Eleven": "Millie",
        "Mike": "Finn",
        "Will": "Noah"}

with open('app.json', 'w') as f:
    json.dump(data, f)

Output

In your app.json file, you have the data json written.

utf8-encode

If we want to get the utf8-encoded, then write the following code.

# app.py

import json

data = {"Eleven": "Millie",
        "Mike": "Finn",
        "Will": "Noah"}

with open('app.json', 'w', encoding='utf-8') as f:
    json.dump(data, f, ensure_ascii=False, indent=4)

The following indented output will be written in the file.

Output

{
    "Eleven": "Millie",
    "Mike": "Finn",
    "Will": "Noah"
}

We can get the utf8-encoded file instead of ASCII-encoded using the following code.

# app.py

import json

data = {"Eleven": "Millie",
        "Mike": "Finn",
        "Will": "Noah"}

with open('app.json', 'w', encoding='utf-8') as f:
    f.write(json.dumps(data, ensure_ascii=False))

Output

{"Eleven": "Millie", "Mike": "Finn", "Will": "Noah"}

On Windows, the encoding=’utf-8′ argument to open is still necessary.

We can avoid storing an encoded copy of the data in memory (the result of dumps), and to output utf8-encoded bytestrings in Python 2 and 3, use the following code.

import json, codecs
with open('app.txt', 'wb') as f:
    json.dump(data, codecs.getwriter('utf-8')(f), ensure_ascii=False)

The codecs.getwriter() function call is redundant in Python 3 but required for Python 2.

How to Convert JSON to List in Python

To convert the JSON to an Object type in Python, use the json.loads() method. The json.loads() is a built-in method that takes a json string as an argument and returns the Python object.

# app.py

import json

array = '{"drinks": ["coffee", "tea", "water"]}'
data = json.loads(array)

for element in data['drinks']:
    print(element)

Output

➜  pyt python3 app.py
coffee
tea
water
➜  pyt

Conclusion

The fast and efficient way to convert a list to json is to use the json.dumps() inbuilt function. 

Always use the json.dumps() function to convert a list of lists to json or a list of dictionaries to json.

Use the json.dump() function to write a json data to a file.

To convert json to a list, you can use the json.loads() function.

That’s pretty much it for this important tutorial.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.