在Python中打开和读取JSON文件通常涉及以下步骤:
1. 导入`json`模块。
2. 使用`open()`函数以读取模式(`'r'`)打开文件。
3. 使用`json.load()`函数将文件内容加载为Python对象。
下面是一个具体的示例代码:
import json
打开JSON文件
with open('data.json', 'r') as file:
加载JSON数据
data = json.load(file)
输出读取到的数据
print(data)
请确保将`data.json`替换为您要读取的JSON文件的实际路径。如果文件路径是相对路径,请确保它在当前工作目录下,或者提供绝对路径。
如果JSON文件格式不符合预期,可能会引发`JSONDecodeError`异常,您可以通过`try`和`except`语句来处理这种情况:
import json
try:
with open('data.json', 'r') as file:
data = json.load(file)
except json.JSONDecodeError as e:
print('Invalid JSON:', e)
如果您需要将Python对象转换为JSON格式并写入文件,可以使用`json.dumps()`函数:
import json
创建一个Python对象
data = {
'name': 'Tom',
'age': 25,
'address': {
'city': 'Beijing',
'street': 'Nanjing Road'
}
}
将Python对象转换为JSON格式
json_data = json.dumps(data)
将JSON数据写入文件
with open('data.json', 'w') as file:
file.write(json_data)
请根据您的具体需求调整代码。