本教程演示了如何使用JavaScript从远程服务器收到的有效解析JSON数据。 我们将分两个步骤介绍该过程:将JSON字符串解码为可用的JavaScript结构(对象或数组),然后遍历该结构以访问数据。 我们将使用XMLHttpRequest
和更现代的fetch
api的实践示例。
密钥概念:
for...in
Object.entries
Object.values
forEach
理解JSON:> json对象:
>名称/值对的集合(类似于JavaScript对象)。
>让我们以api(一个简单的笑话API)为例。 此API返回JSON数据时,将标题设置为XMLHttpRequest
>。>。
icanhazdadjoke
响应是字符串。 我们使用Accept
:application/json
对其进行解析。
>现在,我们可以迭代对象的属性。 以下是几种方法:
const xhr = new XMLHttpRequest(); xhr.onreadystatechange = () => { if (xhr.readyState === XMLHttpRequest.DONE) { console.log(typeof xhr.responseText); // Output: string console.log(xhr.responseText); // Output: JSON string } }; xhr.open('GET', 'https://icanhazdadjoke.com/', true); xhr.setRequestHeader('Accept', 'application/json'); xhr.send(null);
JSON.parse()
if (xhr.readyState === XMLHttpRequest.DONE) { const response = JSON.parse(xhr.responseText); console.log(response); // Output: Parsed JavaScript object }
for...in
:for (const key in response) { if (response.hasOwnProperty(key)) { console.log(`${key}: ${response[key]}`); } }
Object.entries()
api:Object.entries(response).forEach(([key, value]) => { console.log(`${key}: ${value}`); });
解析响应主体作为JSON,并返回通过解析数据解决的诺言。fetch
>让我们从GitHub API中获取一个存储库列表:fetch
(async () => { const response = await fetch('https://icanhazdadjoke.com/', { headers: { Accept: 'application/json' }, }); const jsonData = await response.json(); Object.entries(jsonData).forEach(([key, value]) => { console.log(`${key}: ${value}`); }); })();
>或response.json()
)进行更复杂的操作。
结论:
该教程涵盖了使用JavaScript中的JSON响应进行解析和迭代的基本步骤,同时使用XMLHttpRequest
和fetch
> api。请记住在生产环境中处理潜在错误(例如,网络问题,无效的JSON)。 具有基于承诺的方法的API通常是其清洁语法和更好的错误处理功能的首选。
以上是如何通过JavaScript中的JSON响应循环的详细内容。更多信息请关注PHP中文网其他相关文章!