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

解析和处理嵌套JSON数组:JavaScript教程

心靈之曲
发布: 2025-08-04 14:04:01
原创
368人浏览过

解析和处理嵌套json数组:javascript教程

本文档旨在指导开发者如何使用JavaScript解析和处理包含嵌套数组的JSON数据。我们将通过一个实际案例,演示如何从嵌套的“agencies”数组中提取“raw_name”值,并将其展示在网页上。通过学习本文,你将掌握处理复杂JSON结构的技巧,并能灵活地应用于各种数据处理场景。

理解JSON结构

JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,常用于前后端数据传输。一个JSON对象可以包含键值对,其中值可以是基本数据类型(如字符串、数字、布尔值),也可以是另一个JSON对象或数组。

在处理嵌套JSON时,需要理解其层级结构,以便正确地访问和提取所需的数据。例如,以下JSON结构包含一个名为 "results" 的数组,该数组中的每个元素都是一个包含 "agencies" 数组的对象:

{
  "results": [
    {
      "title": "Example Title 1",
      "agencies": [
        {
          "raw_name": "Agency A"
        },
        {
          "raw_name": "Agency B"
        }
      ]
    },
    {
      "title": "Example Title 2",
      "agencies": [
        {
          "raw_name": "Agency C"
        }
      ]
    }
  ]
}
登录后复制

使用JavaScript解析JSON

JavaScript提供了 JSON.parse() 方法,可以将JSON字符串转换为JavaScript对象。一旦JSON数据被解析为JavaScript对象,就可以使用点号 . 或方括号 [] 访问其属性。

立即学习Java免费学习笔记(深入)”;

以下代码展示了如何使用 XMLHttpRequest 获取JSON数据,并将其解析为JavaScript对象:

const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
  const myArr = JSON.parse(this.responseText);
  // 在这里处理解析后的JSON数据
};
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();
登录后复制

遍历嵌套数组并提取数据

要从嵌套的 "agencies" 数组中提取 "raw_name" 值,可以使用嵌套循环或 map() 方法。

Find JSON Path Online
Find JSON Path Online

Easily find JSON paths within JSON objects using our intuitive Json Path Finder

Find JSON Path Online 30
查看详情 Find JSON Path Online

使用 map() 和 join()

map() 方法可以遍历数组中的每个元素,并返回一个新的数组,其中包含对每个元素应用函数后的结果。join() 方法可以将数组中的所有元素连接成一个字符串,并使用指定的分隔符分隔它们。

以下代码展示了如何使用 map() 和 join() 方法提取 "raw_name" 值,并将它们连接成一个字符串:

  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>";
  }
登录后复制

这段代码首先遍历 myArr.results 数组中的每个元素。对于每个元素,它使用 map(a => a.raw_name) 提取 "agencies" 数组中每个对象的 "raw_name" 值,并将它们存储在一个新的数组中。然后,它使用 join(', ') 将这个新的数组中的所有元素连接成一个字符串,并使用逗号和空格作为分隔符。最后,它将这个字符串添加到 text 变量中。

代码示例

完整的代码示例如下:

<html>
<head>
<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>
  <p id="demo"></p>

  <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>
登录后复制

注意事项

  • 错误处理: 在访问嵌套属性之前,请确保它们存在。可以使用条件语句或 try...catch 块来处理可能出现的错误。
  • 数据类型: 确保JSON数据的类型与预期一致。如果数据类型不正确,可能会导致错误或意外的结果。
  • API限制: 在使用第三方API时,请仔细阅读其文档,了解其使用限制和最佳实践。

总结

本文介绍了如何使用JavaScript解析和处理包含嵌套数组的JSON数据。通过使用 JSON.parse() 方法将JSON字符串转换为JavaScript对象,并使用 map() 和 join() 方法提取和格式化所需的数据,可以轻松地处理复杂的JSON结构。在实际开发中,请注意错误处理和数据类型,并根据API的限制进行调整。 掌握这些技巧,将使你能够更有效地处理各种数据处理场景。

以上就是解析和处理嵌套JSON数组:JavaScript教程的详细内容,更多请关注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号