--- title: Response.json() slug: Web/API/Response/json translation_of: Web/API/Response/json tags: - API - Fetch - JSON - Method - Reference - Response browser-compat: api.Response.json ---
json() 方法接收一个 {{domxref("Response")}} 流,并将其读取完成。它返回一个 Promise,Promise 的解析 resolve 结果是将文本体解析为 {{jsxref("JSON")}}。response.json().then(data => {
// do something with your data
});
没有。
返回一个被解析为JSON格式的promise对象,这可以是任何可以由JSON表示的东西 - 一个object,一个array,一个string,一个number...
在我们的 fetch json 示例 中(运行 fetch json live), 我们使用 {{domxref("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 |
|---|---|---|
| {{SpecName("Fetch", "#dom-body-json", "Response.json()")}} | {{Spec2("Fetch")}} | Initial definition |
{{Compat("api.Response.json")}}