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

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…

If you run the code snippet above, you should get the following output…

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…

If you run the code snippet above, you should get the following output…

That is all, thanks for reading. Please use the comments section below for questions.

Tags:,
One Comment

Add a Comment

Your email address will not be published. Required fields are marked *