JSON.parse() 和 .json() 之间的区别

问题描述 投票:0回答:1

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);
}
javascript json api fetch-api
1个回答
0
投票

您误解了这些方法的作用。

const data = res.json()

这会将

res
中的文本缓冲区解码为 Javascript 对象。这意味着它不再是文本。

const data1 = JSON.parse(res);

这没有任何意义。您正在尝试解析 JS 对象。

© www.soinside.com 2019 - 2024. All rights reserved.