// 将 JavaScript 字符串转换为 JSON 对象的示例代码
// 示例字符串
let jsonString = '{"name": "Alice", "age": 25, "city": "Beijing"}';
// 使用 JSON.parse() 方法将字符串转换为 JSON 对象
try {
let jsonObject = JSON.parse(jsonString);
console.log(jsonObject);
// 输出: { name: 'Alice', age: 25, city: 'Beijing' }
// 访问 JSON 对象中的属性
console.log(jsonObject.name); // 输出: Alice
console.log(jsonObject.age); // 输出: 25
console.log(jsonObject.city); // 输出: Beijing
} catch (error) {
console.error("解析 JSON 字符串时出错:", error);
}
jsonString 是一个符合 JSON 格式的字符串。try-catch 块来捕获并处理可能的异常。如果你需要将 JSON 对象转换回字符串,可以使用 JSON.stringify() 方法。
下一篇:js 调用接口
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站