React Native网络请求JSON提取指定字段问题及undefined原因求助
React Native接口数据提取问题解答
我刚接触React Native,调用接口后获取到如下JSON数据:
{"person":[{"girl":{"name":"Alice","id":1},"boy":{"name":"Json","id":2}},{"girl":{"name":"Sophia","id":3},"boy":{"name":"Mark","id":4}}]}需要提取该JSON中所有的name字段(即Alice、Json、Sophia、Mark),同时想了解如何单独提取Mark的name字段。但编写的代码执行后,
console.log(deserializedObject.lines.sname)返回undefined,请问该问题原因是什么?如何实现需求?代码如下:async getDid () { let httpResponse = await fetch("https://ewserver.di.unimi.it/mobicomp/treest/getLines.php", { method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify({sid:"Zcoc8cPbnTeXrVJB"}) }); const status = httpResponse.status; if (status == 200) { let deserializedObject = await httpResponse.json(); console.log(deserializedObject.lines.sname); return deserializedObject; } else { let error = new Error("Error message from the server. HTTP status: " + status); throw error; }; }
为什么deserializedObject.lines.sname返回undefined
你访问的lines和sname字段在接口返回的JSON结构里完全不存在。返回的根结构是包含person数组的对象,没有lines属性,自然访问deserializedObject.lines会得到undefined,再访问sname也还是undefined。
提取所有name字段的实现
通过遍历person数组,逐个取出每个元素里girl和boy的name字段,收集到数组中即可:
async getDid () { let httpResponse = await fetch("https://ewserver.di.unimi.it/mobicomp/treest/getLines.php", { method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify({sid:"Zcoc8cPbnTeXrVJB"}) }); const status = httpResponse.status; if (status == 200) { let deserializedObject = await httpResponse.json(); // 提取所有name字段 const allNames = []; deserializedObject.person.forEach(item => { allNames.push(item.girl.name); allNames.push(item.boy.name); }); console.log('所有name字段:', allNames); // 输出 ["Alice", "Json", "Sophia", "Mark"] return deserializedObject; } else { let error = new Error("Error message from the server. HTTP status: " + status); throw error; }; }
单独提取Mark的name字段
根据返回的JSON结构,Mark在person数组的第2个元素(数组索引从0开始,对应索引1)的boy对象里,直接通过路径访问即可:
// 在获取deserializedObject之后 const markName = deserializedObject.person[1].boy.name; console.log('Mark的name:', markName); // 输出 "Mark"
如果不确定Mark的位置,也可以通过遍历查找:
// 查找Mark的name const markName = deserializedObject.person.flatMap(item => [item.girl, item.boy]).find(person => person.name === 'Mark')?.name;
内容的提问来源于stack exchange,提问作者Elly
相关产品推荐
相关产品推荐

