--- title: Body.json() slug: Web/API/Body/json tags: - API - BODY - Experimental - Fetch - JSON - Method - Reference - メソッド translation_of: Web/API/Body/json ---
{{DOMxRef("Body")}} ミックスインの json() メソッドは、 {{DOMxRef("Response")}} ストリームを取得して、完全に読み取ります。 ボディのテキストを {{JSxRef("JSON")}} として解釈した結果で解決する promise を返します。
response.json().then(data => {
// data を使用した処理を実行する
});
なし。
JavaScript オブジェクトに解決される {{jsxref("Promise")}}。 このオブジェクトは、オブジェクト、配列、文字列、数値など、JSON で表現できるものであれば何でもなります。
fetch json の例(fetch json をライブで実行)では、 {{DOMxRef("Request.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);
}
});
| 仕様 | 状態 | コメント |
|---|---|---|
| {{SpecName("Fetch", "#dom-body-json", "Body.json()")}} | {{Spec2("Fetch")}} | 初期定義 |
{{Compat("api.Body.json")}}