Fetch获取JSON响应后替换字符串报错:Uncaught ReferenceError: json is not defined
问题解决:Fetch响应替换内容时的ReferenceError错误
错误原因
你的代码里第二个.then()没有传入回调函数,而是直接执行json.replace(...)——这时候json变量根本还没被定义,所以触发了ReferenceError。.then()必须接收一个函数,这个函数会拿到上一步返回的结果作为参数。
正确写法
分两种情况处理:
情况1:API返回的是纯字符串
如果接口直接返回类似"100 Dollar and null Cent"的字符串,代码改成这样:
fetch('https://api.foo.bar/5H2F8QXNTRW7P7LNL1KHXL76JQXXI2') .then(response => response.text()) // 纯字符串用text()更合适,也可继续用json()如果接口返回JSON格式的字符串 .then(rawStr => rawStr.replace(" and null Cent", "")) .then(cleanedStr => document.getElementById("betrag").innerHTML = cleanedStr) .catch(err => console.log('Request Failed', err));
情况2:API返回的是JSON对象
如果接口返回的是包含目标字符串的对象(比如{ value: "200 Euro and null Cent" }),需要针对具体属性处理:
fetch('https://api.foo.bar/5H2F8QXNTRW7P7LNL1KHXL76JQXXI2') .then(response => response.json()) .then(data => { // 替换对象里的目标属性值 data.value = data.value.replace(" and null Cent", ""); return data; }) .then(cleanedData => document.getElementById("betrag").innerHTML = cleanedData.value) .catch(err => console.log('Request Failed', err));
关键注意点
- 不能直接在
.then()里写表达式,必须传一个接收上一步结果的函数; - 如果处理的是JSON对象,不能直接对整个对象调用
replace(对象没有这个方法),要定位到具体的字符串属性再操作。
内容的提问来源于stack exchange,提问作者ThreadStarter
相关产品推荐
相关产品推荐

