JSON.parse() 和 .json() 方法有什么区别?
根据互联网上的一些文章,这两种方法可以以类似的方式工作,并且可以使用一种方法代替另一种方法。但当我尝试时,情况并非如此。 例如:
const URL = "...some url...";
const getResponse = async () => {
const res = await fetch(URL);
const data = await res.json();
console.log(data);
//following part is not working...
const data1 = JSON.parse(res);
consoloe.log(data1);
}
您误解了这些方法的作用。
const data = res.json()
这会将
res
中的文本缓冲区解码为 Javascript 对象。这意味着它不再是文本。
const data1 = JSON.parse(res);
这没有任何意义。您正在尝试解析 JS 对象。