React Native中如何通过fetch方法正确提取JSON返回的指定键值
问题根因
你遇到提取值返回undefined的核心原因是接口返回的JSON是数组包裹的单个对象结构,并非直接返回独立键值对对象:
你给出的成功场景返回结构为:
[ { "iuf": "1366701", "ind": "LEBRUN Léo (2000) H FRA - CN BEAUPREAU", "sex": "#1e90ff", "clb": "CN BEAUPREAU" } ]
之前的代码直接从数组本身读取ind属性,自然拿不到对应值——ind是数组下第一个元素的属性,不是数组自身的属性。
修正后的可用代码
checkLogin = () => { const { name, surname } = this.state; // 对查询参数做转义,避免空格、特殊字符导致请求异常 const searchKey = encodeURIComponent(`${name} ${surname}`) fetch(`https://ffn.extranat.fr/webffn/_recherche.php?go=ind&idrch=${searchKey}`, { method: 'GET', }) .then(response => response.json()) .then(responseJson => { // 兼容两种返回结构:找到用户时返回数组、未找到时直接返回对象 const targetEntry = Array.isArray(responseJson) ? responseJson[0] : responseJson; const indContent = targetEntry?.ind; if (indContent === 'Individu non trouvé !') { alert("Id incorrect") } else { alert("Id correct"); // 现在可以正常提取到指定键值了 alert(JSON.stringify(indContent)) } }) .catch(error => { console.error(error); }); }
实操注意事项
fetch链式调用里的response.json()已经自动完成了JSON字符串到JS对象的转换,不需要再额外手动调用JSON.parse解析重复内容,否则反而会触发解析报错。- 增加结构判断逻辑后,可以覆盖接口不同场景的返回格式差异:不会因为“找到用户返回数组、找不到用户返回对象”的结构变化,出现新的读取错误。
- 拼接带特殊字符的查询参数时统一用
encodeURIComponent转义,避免名字中的空格、法语特殊字符导致请求参数截断。
内容的提问来源于stack exchange,提问作者MathisPoirier
相关产品推荐
相关产品推荐

