JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,易于人阅读和编写,也易于机器解析和生成。它基于JavaScript的一个子集,但独立于语言,被广泛用于Web应用和API中。
import json
# 读取JSON文件
def read_json_file(file_path):
try:
with open(file_path, 'r', encoding='utf-8') as file:
data = json.load(file)
return data
except FileNotFoundError:
print(f"文件 {file_path} 不存在")
except json.JSONDecodeError:
print(f"文件 {file_path} 不是有效的JSON格式")
except Exception as e:
print(f"读取文件时发生错误: {str(e)}")
# 使用示例
data = read_json_file('example.json')
print(data)
import json
# 写入JSON文件
def write_json_file(file_path, data, indent=4):
try:
with open(file_path, 'w', encoding='utf-8') as file:
json.dump(data, file, ensure_ascii=False, indent=indent)
print(f"数据已成功写入 {file_path}")
except Exception as e:
print(f"写入文件时发生错误: {str(e)}")
# 使用示例
data_to_write = {
"name": "张三",
"age": 30,
"is_student": False,
"courses": ["数学", "物理", "化学"]
}
write_json_file('output.json', data_to_write)
const fs = require('fs');
// 读取JSON文件
function readJsonFile(filePath) {
try {
const rawData = fs.readFileSync(filePath, 'utf8');
return JSON.parse(rawData);
} catch (error) {
if (error.code === 'ENOENT') {
console.error(`文件 ${filePath} 不存在`);
} else if (error instanceof SyntaxError) {
console.error(`文件 ${filePath} 不是有效的JSON格式`);
} else {
console.error(`读取文件时发生错误: ${error.message}`);
}
return null;
}
}
// 使用示例
const data = readJsonFile('example.json');
console.log(data);
const fs = require('fs');
// 写入JSON文件
function writeJsonFile(filePath, data, indent = 4) {
try {
const jsonString = JSON.stringify(data, null, indent);
fs.writeFileSync(filePath, jsonString, 'utf8');
console.log(`数据已成功写入 ${filePath}`);
} catch (error) {
console.error(`写入文件时发生错误: ${error.message}`);
}
}
// 使用示例
const dataToWrite = {
name: "李四",
age: 25,
isStudent: true,
courses: ["语文", "历史", "地理"]
};
writeJsonFile('output.json', dataToWrite);
// 假设从API获取JSON数据
fetch('data.json')
.then(response => {
if (!response.ok) {
throw new Error('网络响应不正常');
}
return response.json();
})
.then(data => {
console.log('获取到的JSON数据:', data);
// 处理数据...
// 将数据转换为JSON字符串(例如用于发送到服务器)
const jsonString = JSON.stringify(data);
console.log('JSON字符串:', jsonString);
})
.catch(error => {
console.error('处理JSON时发生错误:', error);
});
encoding='utf-8'
参数try-catch
捕获JSON解析错误fs.createReadStream
)ijson
库处理大型JSON文件没有搜到相关的文章