![]() |
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 Convert List to JSON in PythonBelow are some of the ways by which we can convert a list to JSON in Python:
Using json.dumps() MethodIn this example, a Python list containing a mix of integers and strings ( Python3
Output
<class 'list'> Real List: [1, 2, 3, 'four', 'five'] <class 'str'> Json List: [1, 2, 3, "four", "five"] Using json.dump() MethodIn this example, a list of lists ( Python3
mydata.json [["1", "2", "3"], ["4", "5", "6"], ["7", "8", "9"]] Using json.JSONEncoderIn 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
Output
<class 'list'> [["1", "2", "3"], ["4", "5", "6"], ["7", "8", "9"]] <class 'str'> |
Reffered: https://www.geeksforgeeks.org
Python |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 13 |