Python JSON文件读取
在Python中,我们经常需要处理JSON(JavaScript Object Notation)格式的数据。JSON是一种轻量级的数据交换格式,易于阅读、写入和解析。本文将介绍如何使用Python读取JSON文件,并演示一些实用的示例代码。
读取JSON文件
Python中可以使用json
模块来读取和解析JSON数据。首先,我们需要先导入json
模块,然后使用json.load()
方法来读取JSON文件。
import json
# 读取json文件
with open('data.json', 'r') as file:
data = json.load(file)
print(data)
上面的代码打开名为data.json
的JSON文件,然后使用json.load()
方法将文件中的数据加载到变量data
中。接下来,我们可以对data
进行遍历和操作。
示例代码
示例1: 读取JSON文件中的数据
假设我们有一个名为data.json
的JSON文件,内容如下:
{
"name": "geek-docs.com",
"age": 27,
"website": "https://www.geek-docs.com"
}
我们可以使用以下代码读取并打印出JSON文件中的数据:
import json
# 读取json文件
with open('data.json', 'r') as file:
data = json.load(file)
print(data)
运行结果:
{'name': 'geek-docs.com', 'age': 27, 'website': 'https://www.geek-docs.com'}
通过以上示例代码,我们成功读取到了JSON文件中的数据,并将其打印出来。
示例2: 遍历JSON数据
假设我们有一个名为data.json
的JSON文件,内容如下:
{
"fruits": ["apple", "banana", "orange"],
"prices": {"apple": 2, "banana": 1, "orange": 1.5}
}
我们可以使用以下代码遍历JSON文件中的数据:
import json
# 读取json文件
with open('data.json', 'r') as file:
data = json.load(file)
# 遍历fruits
for fruit in data['fruits']:
print(fruit)
# 遍历prices
for fruit, price in data['prices'].items():
print(fruit, price)
运行结果:
apple
banana
orange
apple 2
banana 1
orange 1.5
通过以上示例代码,我们成功遍历了JSON文件中的数据,并将其打印出来。
总结
本文介绍了如何使用Python读取JSON文件,并演示了一些实用的示例代码。通过学习和实践,我们可以更加熟练地处理JSON数据,为我们的编程工作提供更多便利。