如何通过 JSON.parse() 方法在 JavaScript 中将服务器返回的字符串转换成对象?

2026-05-03 02:003阅读0评论SEO资源
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计531个文字,预计阅读时间需要3分钟。

如何通过 JSON.parse() 方法在 JavaScript 中将服务器返回的字符串转换成对象?

若要直接使用 JSON.parse() 进行解析,请确保输入的字符串是合法的 JSON 格式。若输入的字符串格式不正确,则会报错。

确认响应字符串符合 JSON 规范

服务器返回的必须是标准 JSON 字符串,比如:

  • "{'name': '张三'}" ❌(单引号不合法)
  • '{"name": "张三"}' ✅(双引号 + 外层用单引号或反引号包裹)
  • '{"id": 123, "active": true, "tags": ["js", "json"]}'

常见错误来源:后端误用 toString()、拼接字符串、或返回了 HTML/文本混合内容。可在控制台先打印原始响应,用在线 JSON 验证工具(如 jsonlint.com)检查格式。

基础用法:直接解析

拿到响应体字符串后,传给 JSON.parse() 即可:

立即学习“Java免费学习笔记(深入)”;

const responseText = '{"username":"alice","age":28}'; const user = JSON.parse(responseText); console.log(user.username); // "alice" console.log(typeof user); // "object"

加错误处理,避免崩溃

网络响应可能不是 JSON,或格式出错。务必用 try...catch 包裹:

function safeParse(jsonStr) { try { return JSON.parse(jsonStr); } catch (err) { console.error('JSON 解析失败:', err.message); return null; // 或抛出自定义错误、返回默认值 } } // 使用示例 const data = safeParse(responseText); if (data) { console.log(data); } else { alert('数据加载异常,请重试'); }

配合 fetch 使用的典型流程

现代项目多用 fetch,它本身提供 .json() 方法,内部已封装 JSON.parse 和错误处理:

fetch('/api/user') .then(res => { if (!res.ok) throw new Error(`HTTP ${res.status}`); return res.json(); // 自动调用 JSON.parse,失败时 reject }) .then(user => console.log(user)) .catch(err => console.error('请求或解析出错:', err));

如果手动读取 res.text(),再解析,则需自己加 try/catch

本文共计531个文字,预计阅读时间需要3分钟。

如何通过 JSON.parse() 方法在 JavaScript 中将服务器返回的字符串转换成对象?

若要直接使用 JSON.parse() 进行解析,请确保输入的字符串是合法的 JSON 格式。若输入的字符串格式不正确,则会报错。

确认响应字符串符合 JSON 规范

服务器返回的必须是标准 JSON 字符串,比如:

  • "{'name': '张三'}" ❌(单引号不合法)
  • '{"name": "张三"}' ✅(双引号 + 外层用单引号或反引号包裹)
  • '{"id": 123, "active": true, "tags": ["js", "json"]}'

常见错误来源:后端误用 toString()、拼接字符串、或返回了 HTML/文本混合内容。可在控制台先打印原始响应,用在线 JSON 验证工具(如 jsonlint.com)检查格式。

基础用法:直接解析

拿到响应体字符串后,传给 JSON.parse() 即可:

立即学习“Java免费学习笔记(深入)”;

const responseText = '{"username":"alice","age":28}'; const user = JSON.parse(responseText); console.log(user.username); // "alice" console.log(typeof user); // "object"

加错误处理,避免崩溃

网络响应可能不是 JSON,或格式出错。务必用 try...catch 包裹:

function safeParse(jsonStr) { try { return JSON.parse(jsonStr); } catch (err) { console.error('JSON 解析失败:', err.message); return null; // 或抛出自定义错误、返回默认值 } } // 使用示例 const data = safeParse(responseText); if (data) { console.log(data); } else { alert('数据加载异常,请重试'); }

配合 fetch 使用的典型流程

现代项目多用 fetch,它本身提供 .json() 方法,内部已封装 JSON.parse 和错误处理:

fetch('/api/user') .then(res => { if (!res.ok) throw new Error(`HTTP ${res.status}`); return res.json(); // 自动调用 JSON.parse,失败时 reject }) .then(user => console.log(user)) .catch(err => console.error('请求或解析出错:', err));

如果手动读取 res.text(),再解析,则需自己加 try/catch