Response.json()

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since March 2017.

json()Response インターフェイスのメソッドで、 Response のストリームを取得して完全に読み取ります。本体のテキストを JSON として解釈した結果で解決するプロミスを返します。

なお、このメソッドは json() という名前であるにもかかわらず、結果は JSON ではありません。入力として JSON を取って解釈し、 JavaScript のオブジェクトを生成します。

構文

js
json()

引数

なし。

返値

JavaScript オブジェクトに解決される Promise。 このオブジェクトは、オブジェクト、配列、文字列、数値など、JSON で表現できるものであれば何でもなります。

fetch json の例fetch json をライブで実行)では、 Request() コンストラクターを使用して新しいリクエストを作成し、それを使用して .json ファイルを読み取ります。読み取りに成功したら、json() を使用してデータを読み取り、解析し、結果のオブジェクトから期待通りに値を読み出し、それらの値をリスト項目に追加して商品データとして表示します。

js
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) {
      const 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);
    }
  })
  .catch(console.error);

仕様書

Specification
Fetch Standard
# ref-for-dom-body-json①

ブラウザーの互換性

BCD tables only load in the browser

関連情報