How to parse a JSON file and extract data using Python?
In Python, you can use the json module to parse JSON files and extract data. Here is a simple example:
import json
# 读取JSON文件
with open('data.json', 'r') as file:
data = json.load(file)
# 提取数据
name = data['name']
age = data['age']
city = data['address']['city']
print(f"Name: {name}")
print(f"Age: {age}")
print(f"City: {city}")
In this example, we first use the open() function to open a JSON file, and then use the json.load() function to load the file contents into a Python object.
Next, we can extract JSON data by accessing the keys of Python objects. In this example, we extracted the city field from the name, age, and address keys.
Finally, we print the extracted data using the print() function.
Please note that this example assumes the structure of the JSON file is as follows:
{
"name": "John",
"age": 30,
"address": {
"city": "New York"
}
}
You need to extract data based on the structure of your JSON file.