Body.json()

Body  mixin 的 json() 方法接收一个 Response 流,并将其读取完成。它返回一个 Promise,Promise 的解析 resolve 结果是将文本体解析为 JSON

语法

response.json().then(data => {
  // do something with your data
});

参数

没有。

返回值

返回一个被解析为JSON格式的promise对象,这可以是任何可以由JSON表示的东西 - 一个object,一个array,一个string,一个number...

示例

在我们的  fetch json 示例 中(运行 fetch json live), 我们使用 Request.Request 构造函数创建一个新的请求, 然后使用它来获取一个 .json 文件。当获取成功时,我们使用 json() 读取并解析数据,然后像预期的那样从结果对象中读取值,并将其插入到列表项中以显示我们的产品数据。

const myList = document.querySelector('ul');
const myRequest = new Request('products.json');

fetch(myRequest)
  .then(response => response.json())
  .then(data => {
    for (const product of data.products) {
      let listItem = document.createElement('li');
      listItem.appendChild(
        document.createElement('strong')
      ).textContent = product.Name;
      listItem.append(
        ` can be found in ${
          product.Location
        }. Cost: `
      );
      listItem.appendChild(
        document.createElement('strong')
      ).textContent = `£${product.Price}`;
      myList.appendChild(listItem);
    }
  });

规范

Specification Status Comment
Fetch
Body.json()
Living Standard Initial definition

浏览器兼容性

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
json
Experimental
Chrome Full support 42
Full support 42
Full support 41
Disabled
Disabled From version 41: this feature is behind the Experimental Web Platform Features preference. To change preferences in Chrome, visit chrome://flags.
Edge Full support YesFirefox Full support 39
Full support 39
Full support 34
Disabled
Disabled From version 34: this feature is behind the dom.fetch.enabled preference. To change preferences in Firefox, visit about:config.
IE No support NoOpera Full support 29
Full support 29
Full support 28
Disabled
Disabled From version 28: this feature is behind the Experimental Web Platform Features preference.
Safari No support NoWebView Android No support NoChrome Android No support NoFirefox Android No support NoOpera Android Full support 29
Full support 29
Full support 28
Disabled
Disabled From version 28: this feature is behind the Experimental Web Platform Features preference.
Safari iOS No support NoSamsung Internet Android No support No

Legend

Full support  
Full support
No support  
No support
Experimental. Expect behavior to change in the future.
Experimental. Expect behavior to change in the future.
User must explicitly enable this feature.
User must explicitly enable this feature.

相关链接