You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript访问嵌套数组时JSON.parse报错如何解决?

问题原因

  • 你声明的arr是数组结构,不能直接读取数组的content属性,arr.content的取值结果为undefined,将undefined传入JSON.parse方法就会触发你遇到的语法错误。
  • 该数据结构存在多层嵌套转义的JSON字符串,仅解析第一层content之后,内部的fields、options字段依然是JSON字符串格式,需要逐层解析才能拿到完整的嵌套数组结构。

正确实现代码

var arr = [{
    "id": 1,
    "content": "[{\"number\":1,\"name\":\"Image\",\"description\":\"\",\"fields\":\"[{\\\"number\\\":1,\\\"text\\\":\\\"Image Test\\\",\\\"description\\\":\\\"\\\",\\\"responseType\\\":\\\"Image\\\",\\\"options\\\":\\\"[]\\\"},{\\\"number\\\":2,\\\"text\\\":\\\"test2\\\",\\\"description\\\":\\\"\\\",\\\"responseType\\\":\\\"Text\\\",\\\"options\\\":\\\"[]\\\"}]\"}]"
}];

// 第一步:先取数组第一个元素的content,解析第一层JSON
const firstParse = JSON.parse(arr[0].content);
// 第二步:解析第一层结果中的fields字段JSON
firstParse.forEach(item => {
    item.fields = JSON.parse(item.fields);
    // 第三步:解析每个fields中的options字段JSON
    item.fields.forEach(field => {
        field.options = JSON.parse(field.options);
    })
})

console.log(firstParse);

内容的提问来源于stack exchange,提问作者drago

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 12:57:04