// 将 JSON 字符串转换为 JavaScript 对象
// 示例 JSON 字符串
const jsonString = '{"name": "Alice", "age": 25, "isStudent": false}';
// 使用 JSON.parse() 方法将 JSON 字符串转换为对象
try {
const jsonObject = JSON.parse(jsonString);
console.log(jsonObject);
// 输出: { name: 'Alice', age: 25, isStudent: false }
// 访问对象的属性
console.log(jsonObject.name); // 输出: Alice
console.log(jsonObject.age); // 输出: 25
console.log(jsonObject.isStudent); // 输出: false
} catch (error) {
console.error("JSON 解析失败:", error);
}
// 如果需要将 JavaScript 对象转换回 JSON 字符串,可以使用 JSON.stringify()
const obj = { name: "Bob", age: 30, isStudent: true };
const jsonStringified = JSON.stringify(obj);
console.log(jsonStringified);
// 输出: {"name":"Bob","age":30,"isStudent":true}
jsonString 是一个包含 JSON 数据的字符串。下一篇:js json 排序
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站