首页 > web前端 > js教程 > 正文

解析嵌套JSON数组:提取并显示多层级数据

花韻仙語
发布: 2025-08-04 13:22:28
原创
881人浏览过

解析嵌套json数组:提取并显示多层级数据

本文旨在解决从嵌套JSON数组中提取数据并有效展示的问题。通过JavaScript代码示例,详细讲解如何使用map()和join()方法处理多层级的JSON结构,从而避免因索引错误导致代码中断。同时,提供完整的代码示例,包括HTML、CSS和JavaScript,方便读者理解和实践,最终实现从JSON数据中提取所需信息并在网页上清晰呈现。

在处理JSON数据时,经常会遇到嵌套的数组结构,例如一个包含多个对象的数组,而每个对象又包含一个包含多个对象的数组。直接使用索引访问这些嵌套数组可能会导致问题,尤其是在数组长度不确定的情况下。本文将介绍如何使用JavaScript有效地处理这类嵌套JSON数据,并提供一个完整的示例,展示如何从一个包含多个文档信息的JSON响应中提取数据并在网页上显示。

处理嵌套数组

假设我们有如下的JSON数据结构,其中results数组包含多个对象,每个对象都有一个agencies数组,该数组包含了多个机构信息:

{
  "results": [
    {
      "title": "Document Title 1",
      "type": "Notice",
      "abstract": "Document abstract...",
      "document_number": "2023-00001",
      "html_url": "https://example.com/document1",
      "publication_date": "2023-10-26",
      "agencies": [
        {
          "raw_name": "Agency A",
          "name": "Agency A Full Name",
          "id": 1
        },
        {
          "raw_name": "Agency B",
          "name": "Agency B Full Name",
          "id": 2
        }
      ]
    },
    {
      "title": "Document Title 2",
      "type": "Rule",
      "abstract": "Another document abstract...",
      "document_number": "2023-00002",
      "html_url": "https://example.com/document2",
      "publication_date": "2023-10-27",
      "agencies": [
        {
          "raw_name": "Agency C",
          "name": "Agency C Full Name",
          "id": 3
        }
      ]
    }
  ]
}
登录后复制

直接使用索引 myArr.results[i].agencies[0].raw_name 访问 agencies 数组中的第一个机构名称,当某个文档的 agencies 数组只有一个元素时,代码可以正常运行。但是,如果尝试访问 myArr.results[i].agencies[1].raw_name,而该文档的 agencies 数组只有一个元素,则会导致错误,因为索引 1 超出了数组的范围。

为了解决这个问题,我们可以使用 map() 方法遍历 agencies 数组,提取每个机构的 raw_name,然后使用 join() 方法将这些名称连接成一个字符串。

百度智能云·曦灵
百度智能云·曦灵

百度旗下的AI数字人平台

百度智能云·曦灵 83
查看详情 百度智能云·曦灵
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
  const myArr = JSON.parse(this.responseText);

  let text = "";
  for (let i in myArr.results) {
    // 使用 map() 提取 raw_name 并使用 join(', ') 连接
    let agencies = myArr.results[i].agencies.map(a => a.raw_name).join(', ');
    text += "<div class='fed-reg-container'><h2 class='title'>" + myArr.results[i].title + "</h2><p>" + myArr.results[i].type + "</p><p>" + agencies + " Document # " + myArr.results[i].document_number + "</p><p>Posted on: " + myArr.results[i].publication_date + "</p><p>" + myArr.results[i].abstract + "</p><a class='fed-reg-button' href='" + myArr.results[i].html_url + "'>Read More</a></div>";
  }
  text += "";
  document.getElementById("demo").innerHTML = text;
};
xmlhttp.open(
  "GET",
  "https://www.federalregister.gov/api/v1/documents.json?conditions%5Bagencies%5D%5B%5D=agriculture-department&conditions%5Bagencies%5D%5B%5D=federal-highway-administration&conditions%5Bagencies%5D%5B%5D=fish-and-wildlife-service&conditions%5Bagencies%5D%5B%5D=forest-service&conditions%5Bagencies%5D%5B%5D=interior-department&conditions%5Bagencies%5D%5B%5D=international-boundary-and-water-commission-united-states-and-mexico&conditions%5Bagencies%5D%5B%5D=land-management-bureau&conditions%5Bagencies%5D%5B%5D=national-highway-traffic-safety-administration&conditions%5Bagencies%5D%5B%5D=national-park-service&conditions%5Bagencies%5D%5B%5D=reclamation-bureau&conditions%5Bagencies%5D%5B%5D=environmental-protection-agency&conditions%5Bagencies%5D%5B%5D=council-on-environmental-quality&conditions%5Bagencies%5D%5B%5D=safety-and-environmental-enforcement-bureau&conditions%5Bagencies%5D%5B%5D=environment-office-energy-department&conditions%5Bcomment_date%5D%5Bgte%5D=05%2F01%2F2023&conditions%5Bcomment_date%5D%5Blte%5D=01%2F01%2F2050&conditions%5Bterm%5D=arizona&conditions%5Btype%5D%5B%5D=RULE&conditions%5Btype%5D%5B%5D=PRORULE&conditions%5Btype%5D%5B%5D=NOTICE",
  true
);
xmlhttp.send();
登录后复制

这段代码首先使用 map(a => a.raw_name) 遍历 myArr.results[i].agencies 数组,对于每个机构对象 a,提取其 raw_name 属性。map() 方法返回一个新的数组,其中包含了所有机构的 raw_name。然后,使用 join(', ') 方法将这个数组中的所有元素连接成一个字符串,每个元素之间用逗号和空格分隔。

完整的HTML, CSS和JavaScript代码示例

以下是完整的HTML、CSS和JavaScript代码示例,用于从JSON数据中提取数据并在网页上显示。

<!DOCTYPE html>
<html>
<head>
<title>JSON Data Display</title>
<style>
.fed-reg-container {
  background-color: black;
  color: white;
  padding: 20px;
  margin: 20px 0;
}

.title {
  color: #fcb900;
}

.fed-reg-button {
  background-color: #fcb900;
  color: black;
  padding: 10px;
  display: block;
  max-width: 100px;
  text-align: center;
  font-weight: 600;
  text-decoration: none;
}
</style>
</head>
<body>

<div id="demo"></div>

<script>
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
  const myArr = JSON.parse(this.responseText);

  let text = "";
  for (let i in myArr.results) {
    let agencies = myArr.results[i].agencies.map(a => a.raw_name).join(', ');
    text += "<div class='fed-reg-container'><h2 class='title'>" + myArr.results[i].title + "</h2><p>" + myArr.results[i].type + "</p><p>" + agencies + " Document # " + myArr.results[i].document_number + "</p><p>Posted on: " + myArr.results[i].publication_date + "</p><p>" + myArr.results[i].abstract + "</p><a class='fed-reg-button' href='" + myArr.results[i].html_url + "'>Read More</a></div>";
  }
  text += "";
  document.getElementById("demo").innerHTML = text;
};
xmlhttp.open(
  "GET",
  "https://www.federalregister.gov/api/v1/documents.json?conditions%5Bagencies%5D%5B%5D=agriculture-department&conditions%5Bagencies%5D%5B%5D=federal-highway-administration&conditions%5Bagencies%5D%5B%5D=fish-and-wildlife-service&conditions%5Bagencies%5D%5B%5D=forest-service&conditions%5Bagencies%5D%5B%5D=interior-department&conditions%5Bagencies%5D%5B%5D=international-boundary-and-water-commission-united-states-and-mexico&conditions%5Bagencies%5D%5B%5D=land-management-bureau&conditions%5Bagencies%5D%5B%5D=national-highway-traffic-safety-administration&conditions%5Bagencies%5D%5B%5D=national-park-service&conditions%5Bagencies%5D%5B%5D=reclamation-bureau&conditions%5Bagencies%5D%5B%5D=environmental-protection-agency&conditions%5Bagencies%5D%5B%5D=council-on-environmental-quality&conditions%5Bagencies%5D%5B%5D=safety-and-environmental-enforcement-bureau&conditions%5Bagencies%5D%5B%5D=environment-office-energy-department&conditions%5Bcomment_date%5D%5Bgte%5D=05%2F01%2F2023&conditions%5Bcomment_date%5D%5Blte%5D=01%2F01%2F2050&conditions%5Bterm%5D=arizona&conditions%5Btype%5D%5B%5D=RULE&conditions%5Btype%5D%5B%5D=PRORULE&conditions%5Btype%5D%5B%5D=NOTICE",
  true
);
xmlhttp.send();
</script>

</body>
</html>
登录后复制

在这个示例中,HTML定义了一个用于显示数据的 div 元素(id="demo")。CSS提供了基本的样式,使数据显示更清晰。JavaScript代码使用 XMLHttpRequest 从指定的URL获取JSON数据,然后解析数据,并使用 map() 和 join() 方法处理嵌套的 agencies 数组,最后将提取的数据动态地添加到 div 元素中。

注意事项

  • 错误处理: 在实际应用中,需要添加错误处理机制,例如检查 XMLHttpRequest 的状态码,以及处理JSON解析可能出现的异常。
  • 数据验证: 在访问JSON数据之前,应该验证数据的结构和类型是否符合预期,以避免出现意外的错误。
  • 性能优化: 如果JSON数据量很大,可以考虑使用分页加载或虚拟滚动等技术来优化性能。
  • 兼容性: 确保代码在不同的浏览器和设备上都能正常运行。

总结

通过使用 map() 和 join() 方法,我们可以有效地处理嵌套的JSON数组,并从中提取所需的数据。这种方法不仅简洁,而且可以避免因索引错误导致的代码中断。在实际应用中,可以根据具体的需求进行调整和扩展,例如添加更复杂的逻辑来处理不同的数据结构和类型。

以上就是解析嵌套JSON数组:提取并显示多层级数据的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号