下面将带你一步步了解“Python简单读取json文件功能示例”的完整攻略。
什么是JSON文件?
JSON是JavaScript对象表示法(JavaScript Object Notation)的缩写,是一种轻量级的数据格式,通常用于数据交换和存储。使用JSON作为数据传输格式具有结构化、易读、易解析等优点。
Python读取JSON文件
Python自带了json包,用于处理JSON文件。下面我们将演示如何使用Python读取JSON文件。
示例一
假设有以下的JSON文件:
{
"name": "Alice",
"age": 20,
"gender": "Female",
"hobbies": ["Reading", "Swimming", "Traveling"],
"address": {
"country": "China",
"city": "Beijing"
}
}
那么我们可以通过以下代码读取JSON文件并打印数据:
import json
with open('data.json') as f:
data = json.load(f)
print(data)
输出结果如下:
{
"name": "Alice",
"age": 20,
"gender": "Female",
"hobbies": ["Reading", "Swimming", "Traveling"],
"address": {
"country": "China",
"city": "Beijing"
}
}
示例二
假设有以下的JSON文件:
[
{
"name": "Alice",
"age": 20,
"gender": "Female",
"hobbies": ["Reading", "Swimming", "Traveling"],
"address": {
"country": "China",
"city": "Beijing"
}
},
{
"name": "Bob",
"age": 25,
"gender": "Male",
"hobbies": ["Music", "Hiking"],
"address": {
"country": "USA",
"city": "New York"
}
}
]
那么我们可以通过以下代码读取JSON文件并打印数据:
import json
with open('data.json') as f:
data = json.load(f)
for item in data:
print(item)
输出结果如下:
{
"name": "Alice",
"age": 20,
"gender": "Female",
"hobbies": ["Reading", "Swimming", "Traveling"],
"address": {
"country": "China",
"city": "Beijing"
}
}
{
"name": "Bob",
"age": 25,
"gender": "Male",
"hobbies": ["Music", "Hiking"],
"address": {
"country": "USA",
"city": "New York"
}
}
总结
通过上述两个示例,我们可以看到Python读取JSON文件的方法非常简单。使用json包可以轻松实现将JSON文件读取为Python对象,方便进行后续处理。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Python简单读取json文件功能示例 - Python技术站