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
相关产品推荐
相关产品推荐

