// 解析 JSON 字符串为 JavaScript 对象
const jsonString = '{"name": "Alice", "age": 25, "isStudent": false}';
try {
// 使用 JSON.parse() 方法解析 JSON 字符串
const parsedObject = JSON.parse(jsonString);
console.log(parsedObject);
// 输出: { name: 'Alice', age: 25, isStudent: false }
// 访问解析后的对象属性
console.log(`Name: ${parsedObject.name}`); // 输出: Name: Alice
console.log(`Age: ${parsedObject.age}`); // 输出: Age: 25
console.log(`Is Student: ${parsedObject.isStudent}`); // 输出: Is Student: false
} catch (error) {
// 如果 JSON 字符串格式不正确,捕获并处理错误
console.error('Error parsing JSON:', error);
}
jsonString
是一个包含 JSON 数据的字符串。JSON.parse()
方法将 JSON 字符串转换为 JavaScript 对象。try...catch
块来捕获和处理可能的解析错误(例如,如果 JSON 字符串格式不正确)。上一篇:js json解析
下一篇:js 执行顺序
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站