Convert JSON to list in Python

In this tutorial, we are going to to see how to convert JSON to list in Python. JSON stands for JavaScript Object Notation which is specially formatted data used for applications.
We can convert from JSON to Python and vice versa only if they are equivalent to each other like:

  • JSON Object to a Python dictionary.
  • JSON Array to a Python list/tuple.
  • JSON String to a Python str.
  • JSON Number to a Python int/float.

Let’s check out the conversion below.

JSON exists as a string in Python. It is very common nowadays to transmit and receive data or information between a server side and web application in JSON format data.
Python already contains a built-in package json which we can use to work with JSON formatted data in Python.

All we need is to import the json as shown below to use this library:

import json

Convert JSON array to Python list

We know that, JSON array is Python’s list. json.dumps(obj)–>Convert Python object to JSON string. json.loads(“json”) –> Convert JSON string into Python object. Hence, by using json.loads() function, one can simply convert JSON data into Python data. See the following example to know how to use it.

import json

array = '{"Technology": ["AI", "ML", "DataScience"]}'
data  = json.loads(array)
print (data['Technology'])

Output:

['AI', 'ML', 'DataScience']

Initially, we declared a JSON array, ‘array’ which is a string.  json.loads(array) converts JSON array to Python object i.e. list (here) and the value is stored in data variable. Then by using the print statement, we printed out the Python list.
Note that,data will be a dict, and data [‘Technology’] will be a list.




Also, read:

 


Leave a Reply

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