JSON.parse()与. .json() [英] JSON.parse() Vs. .json()

查看:110
本文介绍了JSON.parse()与. .json()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近一直在使用fetch API和Promises,并且遇到了.json().通常,.json()返回与JSON.parse相同的输出.我在问题上用谷歌搜索,结果指向了其他方向.

I have been working with fetch API and Promises recently and I came across .json() . Oftentimes .json() returns the same output as JSON.parse. I googled the question and the results pointed in other directions.

具有XHR和JSON.parse的示例:

Example with XHR and JSON.parse:

$('#xhr').click(function(){
  var XHR = new XMLHttpRequest();

  XHR.onreadystatechange = function(){
    if (XHR.status == 200 && XHR.readyState == 4) {
      $('#quote').text(JSON.parse(XHR.responseText)[0]);
    }
  };

  XHR.open("GET", url);
  XHR.send();
});

使用Fetch API的示例:

Example with Fetch API:

$('#fetch').click(function(){
  fetch(url)
  .then(function(res){
    return res.json();
  })
  .then(function(quote){
    $('#quote').text(quote);
  })
  .catch(function(err){
    handleError(err);
  });
});

有人可以解释一下这些看似相似的概念之间的区别吗? 谢谢

Could someone please explain the difference between these seemingly similar concepts ? Thanks

推荐答案

Body.json() 是异步的,并返回一个解析为JavaScript对象的Promise对象. JSON.parse() 是同步的,可以解析字符串并更改返回的JavaScript对象.

Body.json() is asynchronous and returns a Promise object that resolves to a JavaScript object. JSON.parse() is synchronous can parse a string and change the resulting returned JavaScript object.

这篇关于JSON.parse()与. .json()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆