In this tutorial, we will discuss how to parse a list of JSON objects in Python, using the json
module. Parsing JSON data is an important skill for any programmer working with APIs, as it is a common data format often used for transmitting data between a client and a server. We will cover the basics of JSON, how to load a list of JSON objects, and how to parse them in Python.
What is JSON?
JSON objects are made up of key-value pairs, also known as properties, where the key is a string, and the value can be a string, number, boolean, null, array (ordered list of values), or another JSON object. These properties are separated by commas and enclosed in curly braces ({}). An example of a JSON object is shown below:
1 2 3 4 5 |
{ "name": "Alice", "age": 30, "city": "New York" } |
Loading the list of JSON objects
Before we can parse a list of JSON objects, we need to have an example list to work with. Let’s assume we have a file named data.json
with the following content:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
[ { "name": "Alice", "age": 30, "city": "New York" }, { "name": "Bob", "age": 25, "city": "San Francisco" }, { "name": "Charlie", "age": 22, "city": "Los Angeles" } ] |
First, we need to load the content of the data.json
file. We can do this using the open
function and the read
method.
1 2 |
with open("data.json", "r") as file: json_data = file.read() |
Parsing the list of JSON objects
Once we have the data in a string format, we can use the json
module to load and parse the JSON objects. The json.loads()
function converts the JSON string into a Python data structure (in this case, a list of dictionaries).
1 2 3 4 5 6 |
import json with open("data.json", "r") as file: json_data = file.read() data_list = json.loads(json_data) |
Now, with the list of dictionaries representing the JSON objects, you can access the information you need.
Example: Extracting the names of people
Let’s say we want to extract the names of all the people in our list of JSON objects. We can do this by iterating through the list and accessing the “name” property for each dictionary.
1 2 3 4 5 6 |
names = [] for data in data_list: names.append(data["name"]) print(names) |
Output
['Alice', 'Bob', 'Charlie']
Full Code
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import json with open("data.json", "r") as file: json_data = file.read() data_list = json.loads(json_data) names = [] for data in data_list: names.append(data["name"]) print(names) |
Conclusion
In this tutorial, we covered the basics of JSON data and how to parse a list of JSON objects in Python using the json
module. This skill is useful for working with APIs and other data sources that provide data in JSON format. With the ability to parse and manipulate JSON data, you can build more robust applications that handle information from various sources.