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

解析嵌套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() 方法将这些名称连接成一个字符串。

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 += "

" + myArr.results[i].title + "

" + myArr.results[i].type + "

" + agencies + " Document # " + myArr.results[i].document_number + "

Posted on: " + myArr.results[i].publication_date + "

" + myArr.results[i].abstract + "

Read More
"; } 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数据中提取数据并在网页上显示。

JSON Data Display.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;}
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 += "

" + myArr.results[i].title + "

" + myArr.results[i].type + "

" + agencies + " Document # " + myArr.results[i].document_number + "

Posted on: " + myArr.results[i].publication_date + "

" + myArr.results[i].abstract + "

Read More
"; } 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();

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

注意事项

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

总结

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/120373.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2025年11月25日 23:51:55
下一篇 2025年11月25日 23:57:28

相关推荐

发表回复

登录后才能评论
关注微信