--- title: Body.json() slug: orphaned/Web/API/Body/json translation_of: Web/API/Body/json original_slug: Web/API/Body/json ---
{{domxref("Body")}} mixin 的 json() 會拿 {{domxref("Response")}} stream 並完整地讀取他。它會回傳一個能夠實現 (resolve) 把回傳的結果的 body text 解析成 {{jsxref("JSON")}} 型別的 Promise。
response.json().then(function(data) {
// do something with your data
});
None.
一個能夠實現 (resolve) 把回傳的結果的 body text 解析成 JSON 型別的 Promise。這可以是任何能夠被 JSON 呈現的資料型別 — 物件 (object), 陣列 (array), 字串 (string), 數字 (number)...
在我們的範例 fetch json example (run fetch json live) 中,我們用 constructor {{domxref("Request.Request")}} 產生一個新的請求,並且用它去取回 .json 檔案。 當成功取回 (fetch) 時,我們使用 json() 去讀取跟解析資料,然後依照我們期待的把回傳的結果物件 (resulting objects) 裡讀取到的數值存入 list 中藉以顯示我們的產品資料。
var myList = document.querySelector('ul');
var myRequest = new Request('products.json');
fetch(myRequest)
.then(function(response) { return response.json(); })
.then(function(data) {
for (var i = 0; i < data.products.length; i++) {
var listItem = document.createElement('li');
listItem.innerHTML = '<strong>' + data.products[i].Name + '</strong> can be found in ' +
data.products[i].Location +
'. Cost: <strong>£' + data.products[i].Price + '</strong>';
myList.appendChild(listItem);
}
});
| Specification | Status | Comment |
|---|---|---|
| {{SpecName('Fetch','#dom-body-json','json()')}} | {{Spec2('Fetch')}} |
{{Compat("api.Body.json")}}