Converting a list of lists to json in Python
Introduction
JSON (Java Script Object Notation) is one of the most popular text formats on the web due to its simplicity, lightweight and adoption. It is used to structure data exchange between web services. You may check the following article for implementing a simple web service using Python. JSON is a subset of the JavaScript language syntax.
JSON format has the following rules…
- Data is represented in name value pairs separated by commas
- Objects are held in curly braces
- Arrays are held in square brackets
Here is an example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
{ "cars": [ { "id":"01", "model": "Honda", "color": "White" }, { "id":"02", "model": "Ford", "color": "Black" } ] } |
The JSON file above contains information about two cars. Each car object has three fields. It resembles a database table. Car objects are the rows and fields are the columns. Let us now demonstrate how to convert a list of lists in Python to JSON format…
Example
To convert a Python list (or list of lists) to Python string, we use the function json.dumps. Take a look at the follow code snippet…
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
# Import the json module import json # Define a list of lists A = [[1, 2], [3, 4], [5, 6]] # B is going to be the json # representation of A in string format B = json.dumps(A) # If you want to convert the json string # back to list use json.loads() C = json.loads(B) # Print A, B and C to see how they look print(A) print(B) print(C) # Print their types print(type(A)) print(type(B)) print(type(C)) |
If you run the code snippet above, you should get the following output…
1 2 3 4 5 6 |
[[1, 2], [3, 4], [5, 6]] [[1, 2], [3, 4], [5, 6]] [[1, 2], [3, 4], [5, 6]] <type 'list'> <type 'str'> <type 'list'> |
Write read json from to file
Now, if we want to save the converted list to file, we should be able to do so by opening a file for writing and use the json.dumps() function. Let us take a look…
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
# Import the json module import json # Define a list of lists A = [[1, 2], [3, 4], [5, 6]] # Open the file for writing with open('list.json', 'w') as F: # Use the json dumps method to write the list to disk F.write(json.dumps(A)) # To load the list back from disk # Open the file for reading with open('list.json', 'r') as F: B = json.loads(F.read()) # Print the loaded list to see if it looks the same print(A) print(B) # Close the file F.close() |
If you run the code snippet above, you should get the following output…
1 2 |
[[1, 2], [3, 4], [5, 6]] [[1, 2], [3, 4], [5, 6]] |
That is all, thanks for reading. Please use the comments section below for questions.
Thanks for these clear and concise examples. Very useful.
One question though, doesn’t the with statement already close the file?