- Convert Python List to JSON Examples
- 1. Quick Examples of Convert List to JSON
- 2. Syntax of json.dumps() Function
- 3. Convert List to JSON
- 4. Convert List of Dictionaries to JSON
- 5. Convert a List of Lists to JSON
- Conclusion
- You may also like reading:
- Convert a List to JSON String in Python [Easy Step-By-Step]
- Using JSON Module
- JSON Module dumps() Function
- Convert a List to JSON
- Convert a List of Lists to JSON
- Convert a List of Dictionaries to JSON string
- Conclusion
- Read and Write JSON File Python 3
- List of JSON Data Formats
- Using Python 3 to Write JSON
- Sample Code to Create JSON Python3 String
- Sample Code to Create JSON Python3 List
- Sample Code to Create JSON Python3 Tuple
- Sample Code to Create JSON Python3 Dictionary
- Sample Code to Create JSON Python3 List of Lists
- Sample Code to Create JSON Python3 Nested Tuple
- Using JSON Data Like a Table (List of Dictionaries)
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:
Convert a List to JSON String in Python [Easy Step-By-Step]
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.
Read and Write JSON File Python 3
In the most simple form, JSON is a text file containing data. You can however, have very complicated data structures!
List of JSON Data Formats
JSON can be any data format that you choose (some examples):
- Strings
- Lists/Tuples
- Dictionaries
- List of Lists
- Lists of Dictionaries
Whatever your data structure is without JSON, it will remain the same with JSON. JSON is just a way to represent the data, in a text file.
Using Python 3 to Write JSON
Here are some examples of using python JSON module to write sample JSON for you (and their corresponding JSON examples).
Sample Code to Create JSON Python3 String
Creating a string as a JSON file is hardly worth the effort, but in case you wanted to script it, here it is:
Sample Code to Create JSON Python3 List
Here is the Python 3 Script for making a list, and writing it out to a JSON data file:
Sample Code to Create JSON Python3 Tuple
Here is the Python 3 Script for making a tuple and writing it out to a JSON data file:
If you are paying attention, you’ll see that both a list and a tuple look the same in JSON. JSON doesn’t make it a list or a tuple, how you load and use it does!
Sample Code to Create JSON Python3 Dictionary
Dictionaries are quite common when working with JSON, especially as building blocks for more complicated data structures. Here is a python script to create a dictionary file in JSON:
Output sample for a JSON dictionary:
Sample Code to Create JSON Python3 List of Lists
If you wanted to make a list of lists (a matrix) in python and create a json data file, you could do something like this:
Output example of JSON data for a list of lists in JSON:
Sample Code to Create JSON Python3 Nested Tuple
Nested tuples can be created in JSON using python just as simple as any other data format:
Output of a nested tuple in JSON:
Using JSON Data Like a Table (List of Dictionaries)
For the final example, I’ll share how to manipulate JSON data that mimics a table. For this example, I am writing a script to talk to the API on a popular firewall. My script needs to know my current IP (a dynamic DNS). Once I know my IP, then I can open up the firewall. As a “first step”, I needed to have a rule base so I could manage my firewall. This script example is that “first step”.
Common ports I will be working with are 22,80,443:
Here is the sample data I want to load as an initial rule set using those common ports and a structure similar to what I will work with in the final script:
ID | Source IP | Dest IP | Service | Description |
---|---|---|---|---|
100 | 1.2.3.4 | 2.3.4.5 | tcp/22 | Data Center A |
101 | 1.2.3.4 | 2.3.4.5 | tcp/80 | Data Center B |
102 | 1.2.3.4 | 2.3.4.5 | tcp/443 | Data Center B |
My list of dictionaries uses the same keys as part of my logic, like a table header (see example above). I wanted to represent a much more complicated rule set in a spreadsheet for easy human readable audits but use scripting to talk to the API.
In this example we are using a data structure in Python that is a list of dictionaries and I wasn’t quite sure what it was supposed to look like.
The quick solution (instead of looking up data structures), was to just print it out and let Python tell me what it was supposed to look like, so that’s what I did.
Here is the script that printed out my data and json for me using sample data: