List object to json python

How to Convert List to JSON in Python

To convert a list to JSON in Python, you can use the “json.dumps()” function. This function takes a list as an argument and returns a JSON string. For example, if you have a list called main_list = [1, 2, 3], json.dumps() returns json string [1, 2, 3].

Syntax

import json json.dumps(list) 

Example

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

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

How to Convert a List of Dictionaries to JSON

You can use the json.dumps() method to convert a list of dictionaries to JSON. This function preserves the original data and structure of the list of dictionaries.

import json list_of_dicts = [, ] json_str = json.dumps(list_of_dicts) print(json_str)

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

You can use the json.dumps() method to convert 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 input data.

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

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.

import json data =  "Mike": "Finn", "Will": "Noah"> with open('app.json', 'w') as f: json.dump(data, f)

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

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

import json data =  "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.

  "Eleven": "Millie", "Mike": "Finn", "Will": "Noah" >

Источник

Convert a List to JSON String in Python [Easy Step-By-Step]

Convert A List To JSON String

JSON is a widely used format for data exchange between different systems and programming languages. It uses JavaScript notation to store and exchange textual data. It is small in size making it fast to transfer over the network for the transmission of information.

By converting a Python list to JSON, one can utilise its powerful features. We can use the Python json module to convert the Python list to a JSON string.

In this tutorial, we will see a method to convert a list to a JSON string using json module. We’ll also learn how to convert a list of lists and a list of dictionaries to a JSON string. With that being said, let’s dive deeper into the interesting content.

Using JSON Module

The json module in Python is used to work with JSON objects and files. It is a standard Python package that comes with the Python. Hence, we do not have to install it manually on our local system. We can directly import in by using the import statement.

The json module has a function dumps() that is used to convert a list to JSON in Python.

JSON Module dumps() Function

The dumps() function takes a Python list as its parameter, converts it into a JSON string, and then returns that JSON string. The syntax for using the dumps() function is given below.

where the list is a list that you want to convert to a JSON string.

Now, let’s discuss how we can convert the several types of Python lists i.e. a simple list, list of lists, and list of dictionaries to JSON string.

Convert a List to JSON

Let’s start with converting a simple Python list of even numbers. We have to pass the list to the above-discussed json.dumps() function to convert into JSON data string.

# Import json Python module import json # Create a Python list list_1 = [2, 4, 6, 8, 10] # Convert the above Python list to JSON string json_str_1 = json.dumps(list_1) # Check the type of value returned by json.dumps() print(type(json_str_1)) # Print the result print(json_str_1)

Here we have used the type() function to get the data type of the result returned by the json.dumps() function.

In the above output, you are not seeing any difference because the list passed is already a valid JSON array.

Convert a List of Lists to JSON

We can convert a list of lists to a JSON string in the same way as we have done for a list of numbers.

To demonstrate this conversion, we will first create a Python list of lists containing the capital English alphabet characters and their corresponding ASCII codes. Then we will pass it to the json.dumps() function which will return the required JSON string.

# Import json Python module import json # Create a Python list of lists list_2 = [['A', 'B', 'C', 'D', 'E'], [65, 66, 67, 68, 69]] # Convert the above Python list of lists to JSON string json_str_2 = json.dumps(list_2) # Check the type of value returned by json.dumps() print(type(json_str_2)) # Print the result print(json_str_2)

In the above output, you can see that the data type of the returned value is a string which shows that we have successfully converted the list of lists into a JSON string.

Convert a List of Dictionaries to JSON string

We can also convert list of dictionaries to a JSON string by using json.dumps() function.

For example, we will create a Python list of dictionaries containing the odd, even, and prime numbers’ lists corresponding to their keys (labels). Then we will pass it as an argument to the json.dumps() function and print the resultant value in the console.

# Import json Python module import json # Create a Python list of dictionaries list_3 = [, , ] # Convert the above Python list of dictionaries to JSON string json_str_3 = json.dumps(list_3) # Check the type of value returned by json.dumps() print(type(json_str_3)) # Print the result print(json_str_3)

See, we have successfully converted the list of dictionaries into a JSON string.

Conclusion

In this tutorial, we have learned that to convert list to JSON, we can use the json.dumps() method of json module, which takes a list as an argument and returns a json string. This method can convert not only a list of values but also a list of lists and a list of dictionaries into a JSON string. Hope you have understood the concepts discussed above and are ready to try them on your own. Thanks for reading this article! Stay tuned for more such amazing learning material related to Python programming.

Источник

Convert Python List to JSON Examples

How to convert a list to JSON in python? You can use the json.dumps() method to convert a Python list to a JSON string. This function takes a list as an argument and returns the JSON value. The json.dumps() function converts data types such as a dictionary, string, integer, float, boolean, and None into JSON. In this article, I will explain the syntax of how to convert a list to JSON in Python, its parameters, and explain how to use it.

1. Quick Examples of Convert List to JSON

If you are in a hurry, below are some quick examples of how to convert list to JSON.

 # Below are the quick examples # Example 1: Convert python list to JSON numbers = [25, 36, 48, 54] json_numbers = json.dumps(numbers) # Example 2: Convert python string type list to JSON technology = ["Hadoop", "Spark", "Python"] json_string = json.dumps(technology) # Example 3: Convert list of dictionaries to JSON my_dict = [, ] jsondict = json.dumps(my_dict) # Example 4: Convert a list of lists to JSON List = [[], []] jsonList = json.dumps(List) 

2. Syntax of json.dumps() Function

Following is a syntax of the json.dumps() function.

 # Syntax of json.dumps() function import json json.dumps(list) 

You have to import json package to use json.dumps() function.

3. Convert List to JSON

You can use the json module to convert a list to a JSON object. The json.dumps() function converts a Python object, in this case, a list, into a JSON string. You can see that below examples you converted json string to a list using the dumps() method.

 import json # Convert python list to JSON numbers = [25, 36, 48, 54] json_numbers = json.dumps(numbers) print(json_numbers) # Output # [25, 36, 48, 54] import json # Convert python string type list to JSON technology = ["Hadoop", "Spark", "Python"] json_string = json.dumps(technology) print(json_string) # Output # ["Hadoop", "Spark", "Python"] 

4. Convert List of Dictionaries to JSON

The json.dumps() method can be used to convert a list of dictionaries to a JSON string in python. This function converts a list of dictionaries to JSON string without losing any original data.

 import json # Convert list of dictionaries to JSON my_dict = [, ] jsondict = json.dumps(my_dict) print(jsondict) # Output # [, ] 

5. Convert a List of Lists to JSON

You can also use the json.dumps() method to convert a python list of lists to a JSON string, and this process preserves the original data in the lists. For example, JSON string representation of the list of lists, which you can then write to a file or send over a network connection, etc.

 import json # Convert a list of lists to JSON List = [[], []] jsonList = json.dumps(List) print(jsonList) # Output # [[], []] 

Conclusion

In this article, I have explained how to convert a list to JSON in python by using json.dumps() function with examples.

You may also like reading:

Источник

How to Convert a Python List to JSON?

A popular data interchange format for web applications and APIs is JSON or JavaScript Object Notation. Python lists can be converted to JSON for human-readable data interchange.

To convert a list to JSON, the “json.dumps()” function and the “json.JSONEncoder().encode()” function are used in Python, which is briefly explained in this post:

Method 1: Using the json.dumps() Function

A Python object can be converted into a JSON string using the “json.dumps()” function. The “json.dumps()” function serialized a given object into a JSON string. Below is a syntax for “json.dumps()”:

json.dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)

In the above syntax, the parameter “obj” specifies the serialized object. There are optional additional parameters that can be used to customize the serialization process, such as for sorting dictionary keys, the “sort_key” parameter is used; for indentation “indent” parameter is used, etc.

Let’s understand the conversion of a Python list to JSON using various examples:

Example 1: List to JSON

The below code is used to convert the list to json:

import json json_string = json.dumps([45, 55, 60]) print(json_string)
  • The module named “json” is initialized.
  • The “json.dumps()” function accepts the list as an argument/parameter and returns the JSON string.

A JSON representation of the input list has been created.

Example 2: List of Dictionaries to JSON

The below code is used to convert the list of dictionaries to JSON:

import json json_string = json.dumps([, ]) print(json_string)

The “json.dumps()” function takes the list of dictionaries as a parameter and retrieves the JSON strings.

JSON has been created from the input list of dictionaries.

Example 3: List of Lists to JSON

The following example code is utilized to convert the list of lists to JSON:

import json json_string = json.dumps([[23, 12, 55], [12, 3, 5], [1, 5, 22]]) print(json_string)

The “json.dumps()” function takes the list of lists as an argument and converts it into JSON strings.

A JSON string has been created from the input list of lists.

Method 2: Using the json.JSONEncoder().encode()

The “json.JSONEncoder().encode()” function is utilized to convert the Python list to JSON string. The “JSONEncoder” class is used to define the encoding of custom objects, and the “encode()” method is used to encode the object into a JSON string.

import json json_string = json.JSONEncoder().encode([34, 35, 15, 22]) print(json_string)
  • The module named “json” is imported at the start.
  • The “json.JSONEncoder().encode()” accepts the list as an argument/parameter and converts it into a JSON string.

A JSON representation of the input list has been created.

Conclusion

To convert a list, list of dictionaries, or list of lists to JSON, the “json.dumps()” function and the “json.JSONEncoder().encode()” function are used in Python. The “json.dumps()” function takes the list, list of lists, and list of dictionaries as a parameter and converts them into JSON strings. Similarly, the “json.JSONEncoder().encode()” function can convert the list to JSON strings. This post presented various methods to convert a Python list to JSON using numerous examples.

Источник

Читайте также:  Адрес почты
Оцените статью