Python – Print List in JSON format

Python – Print list in JSON format

The JSON equivalent of a Python list is a JSON Array.

To print list in JSON format in Python, you can use json library. Call json.dumps() method and pass the given list as argument. dumps() method returns a JSON formatted version of the given list.

For example, consider the following list.

x = ['apple', 'banana', 100, 200]

The JSON format of this list is given below.

["apple", "banana", 100, 200]

1. Print list in JSON format using json.dumps() method in Python

Consider that we are given a list in x, and we have to print this list in JSON format using json library.

Steps

  1. Import json library.
  2. Given a list in x.
  3. Call json.dumps() method and pass x as argument to the method.
json.dumps(x)
  1. The method returns a JSON array representation of the list. Print it to standard console output using print() built-in function.

Program

The complete program to print a list in JSON format using json.dumps() method.

Python Program

import json

# Given list
x = ['apple', 'banana', 100, 200]

# Convert list to JSON string
x_json = json.dumps(x)

# Print the list in JSON format
print(x_json)
Run Code Copy

Output

["apple", "banana", 100, 200]

The list is printed in JSON format.

Summary

In this tutorial, we have seen how to print a given list in JSON format using json dumps() function, with well detailed examples.

Related Tutorials

Code copied to clipboard successfully 👍