Python Convert List to Json to Share Data: A Beginner Guide

By | April 23, 2020

We can convert python object to json to share data, such as python dictionary to json. How to convert a python list to json? There does not exis any key in a list. In this tutorial, we will introduce you how to do.

Preliminary

We first import json libary and create a python list.

import json

members = [('Tom',23, 'male'),('Kate',22, 'female'),('Lily',23, 'female')]

Convert python list to json

We will create a function to covert.

Here is an example code.

def listToJson(lst):
    keys = [str(x) for x in range(len(lst))]
    list_json = dict(zip(keys, lst))
    str_json = json.dumps(list_json, indent=2, ensure_ascii=False)
    return str_json

Then we can use this function to convert any list variable to json string.

print(listToJson(members))

Run this code, you can get the result.

{
  "0": [
    "Tom",
    23,
    "male"
  ],
  "2": [
    "Lily",
    23,
    "female"
  ],
  "1": [
    "Kate",
    22,
    "female"
  ]
}

Then you can send this json string to other application or servers to share data.

Leave a Reply