This is how to convert a list to a JSON array in Python.
To convert a list to a JSON array is called serialization.
Learn how to serialize and deserialize a list with this in-depth article.
Let’s get started!
Learn How to Convert a List to JSON Array in Python
You learn the structure of JSON objects and why they’re needed.
Then you’ll learn how to convert lists to JSON arrays. This is called serialization.
Next we’ll convert JSON arrays to Python lists. This is called deserialization.
In addition, you’ll figure out how to combine two separate lists with field names and values into a single JSON object.
So first things first:
What’s JSON?
According to json.org, JSON is a lightweight data exchange format. It’s easy for humans to read and write.
Machines can easily interpret and generate JSON.
Don’t be intimidated by JavaScript in the acronym. JSON was born out of this language but turned out to be a great tool for sending data, for example in HTTP requests. It’s compact, lightweight, and easy to read.
So it is easy to transfer it via the network, it is easy to parse, and it is easy to read as simple text.
What Is the Difference Between JSON and XML?
If you’re familiar with XML, then JSON is very similar. There are also fields with names and values.
Let’s compare JSON and XML for the same object.
Here’s the JSON:
[
{
"name":"Alice",
"age": 31,
"children": [
{
"name":"Kate",
"sex":"girl",
"age": 4
},
{
"name":"John",
"sex":"boy",
"age": 2
}
]
},
{
"name":"Bob",
"age": 35,
"children":null
},
{
"name":"Christine",
"age": 25,
"children": [
{
"name":"Ada",
"sex":"girl",
"age": 1
}
]
}
]
Here’s the XML:
<? xml version="1.0" encoding="UTF-8" ?>
<root>
<row>
<name>Alice</name>
<age>31</age>
<children>
<name>Kate</name>
<sex>girl</sex>
<age>4</age>
</children>
<children>
<name>John</name>
<sex>boy</sex>
<age>2</age>
</children>
</row>
<row>
<name>Bob</name>
<age>35</age>
<children />
</row>
<row>
<name>Christine</name>
<age>25</age>
<children>
<name>Ada</name>
<sex>girl</sex>
<age>1</age>
</children>
</row>
</root>
XML looks less readable because of opening and closing tags. Yet, in general, both formats can be read without any extra processing.
JSON Objects and JSON Arrays
Let’s take a look at the JSON object. In this case, it’s an JSON array. It is enclosed in square brackets and can contain values of different types:
- Other JSON arrays
- JSON objects enclosed in curly braces
- Quoted string values
- Numeric values (integer and float)
- Booleans (true or false)
- Empty values (none)
The above array contains three JSON objects separated by commas. Curly braces define JSON objects.
See here for the differences between JSON array and JSON objects.
Let’s look at the first object in the array. It contains a bunch of fields whose names are strings in quotes.
After a field’s name, you write a colon and then its value. The “name” field is a string “Alex”, the “age” field is a number 31, and the “children” field is a JSON array with two JSON objects.
How to Convert a Python List to a JSON Array or Object?
Python has its own module for working with JSON Objects. You can import it like this:
import json
After that you’ll get methods for converting a string or file into a Python object and the other way around.
Python lists are the most similar structure to JSON arrays, so they are converted directly to JSON arrays by using the dumps method:
import json
lst = [1, 2, 3]
json_string = json.dumps(lst)
print(json_string)
[1, 2, 3]
Which Python object is the closest to a JSON object? It stores key-value pairs. if you know even a little Python, you can guess that it’s a dictionary.
The dictionary can also be transformed into a JSON object using the dumps method:
import json
dic = {"a": 1, "b": 2}
json_string = json.dumps(dic)
print(json_string)
{"a": 1, "b": 2}
Let’s build a dictionary corresponding to our JSON object from the array, and convert it to JSON format.
Note that Python will let you put a line break inside any parentheses. Just like tabs and spaces, they are ignored so you can write your object nicely:
import json
dic = {
"name":"Alice",
"age": 31,
"children": [
{
"name":"Kate",
"sex":"girl",
"age": 4
},
{
"name":"John",
"sex":"boy",
"age": 2
}
]
}
json_string = json.dumps(dic)
print(json_string)
{"name": "Alice", "age": 31, "children": [{"name": "Kate", "sex": "girl", "age": 4}, {"name": "John", "sex": "boy", "age": 2}]}
As you can see, the output is a flat string. If you save it to a file, it won’t be very convenient to read. Fortunately, the dumps method has a handy indent parameter that lets you format the string:
import json
dic = {
"name":"Alice",
"age": 31,
"children": [
{
"name": "Kate",
"sex": "girl",
"age": 4
},
{
"name": "John",
"sex": "boy",
"age": 2
}
]
}
json_string = json.dumps(dic, indent = 2)
print(json_string)
{
"name": "Alice",
"age": 31,
"children": [
{
"name": "Kate",
"sex": "girl",
"age": 4
},
{
"name": "John",
"sex": "boy",
"age": 2
}
]
}
This output is way more readable.
How to Convert a JSON Array or Object to a Python List?
In case you want to load an object from JSON into a list, you have to use the loads method.
By the way, converting an object (a list or a Python dictionary, for example) into a JSON string is called serialization, don’t be alarmed when you come across this word.
The reverse process of getting an object from a JSON string is called deserialization.
Let’s deserialize a dictionary from a string:
import json
json_string = '{"name": "Alice", "age": 31, "children": [{"name": "Kate", "sex": "girl", "age": 4}, {"name ": "John", "sex": "boy", "age": 2}]} '
dic = json.loads(json_string)
print(dic["name"])
Alice
When you’ve deserialized a JSON object, you can refer to its fields’ values by their names.
For example, in the example above, you display the value of the field name after deserializing.
Note that the JSON string is in single quotes, and all strings inside the JSON object are in double quotes. If you don’t do this, you’ll have to escape every double quote in the string.
Also, make sure you put the field names in double quotes in the JSON object.
Unlike Python, where you can write string in both single and double quotes, single quotes within an object record will throw an error:
import json
json_string = "{'name': 'Alice', 'age': 31, 'children': [{'name': 'Kate', 'sex': 'girl', 'age': 4}, {'name': 'John', 'sex': 'boy', 'age': 2}]} "
dic = json.loads(json_string)
print(dic["name"])
Traceback (most recent call last):
File "example.py", line 4, in <module>
dic = json.loads (json_string)
File "/usr/lib/python3.7/json/__init__.py", line 348 , in loads
return _default_decoder.decode (s)
File "/usr/lib/python3.7/json/decoder.py", line 337, in decode
obj, end = self.raw_decode (s, idx = _w (s, 0) .end ())
File "/usr/lib/python3.7/json/decoder.py", line 353, in raw_decode
obj, end = self.scan_once (s, idx)
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
How to Convert Multliple Python Lists to a JSON Object?
What if you have two lists?
One with fields and one with values.
How do you convert them to a JSON object in this case?
To do this, you’ll have to convert the lists to a dictionary. You can do this for example with a dictionary comprehension:
You loop through the indexes and fill the dictionary’s keys and values with the values from the lists. Then, you convert the dictionary to JSON with the dumps method:
import json
fields = ["name", "sex", "age"]
values = ["Alice", "female", 30]
dic = {fields[i]: values[i] for i in range (len(fields))}
json_string = json.dumps(dic, indent = 2)
print(json_string)
Output:
{
"name": "Alice",
"sex": "female",
"age": 30
}
Another way is to use the zip function. It takes two lists as input and returns a sequence of tuples with the values from those lists.
The first element of a zip object is the first value of the first list and the first value of the second list.
The second element of a zip object is the second value of the first list and the second value of the second list. And so on.
After that, you can use the dictionary constructor to create the dictionary. Then the dumps method to serialize the dictionary to JSON:
import json
fields = ["name", "sex", "age"]
values = ["Alice", "female", 30]
dic = dict(zip(fields, values))
json_string = json.dumps(dic, indent = 2)
print(json_string)
{
"name": "Alice",
"sex": "female",
"age": 30
}
The second method is the prettier one, but use whichever one suits you.
To serialize and deserialize JSON objects from a file, you can use the dump and load methods. They work just like the dumps and loads methods.