
本文旨在解决从嵌套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 += "<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代码示例,用于从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 元素中。
通过使用 map() 和 join() 方法,我们可以有效地处理嵌套的JSON数组,并从中提取所需的数据。这种方法不仅简洁,而且可以避免因索引错误导致的代码中断。在实际应用中,可以根据具体的需求进行调整和扩展,例如添加更复杂的逻辑来处理不同的数据结构和类型。
以上就是解析嵌套JSON数组:提取并显示多层级数据的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号