JS 读取JSON
在Web开发中,JSON(JavaScript Object Notation)是一种常用的数据交换格式。许多网站和应用程序使用JSON来存储和传输数据。在JavaScript中,我们经常需要读取JSON数据并将其用于网页的展示或交互。本文将详细介绍如何使用JavaScript读取JSON数据。
什么是JSON
JSON是一种轻量级的数据交换格式,易于人阅读和编写,也易于机器解析和生成。JSON由键值对组成,键值对用逗号分隔,键值对之间用花括号包裹,数组中的元素用方括号包裹。以下是一个简单的JSON示例:
{
"firstName": "John",
"lastName": "Doe",
"age": 30,
"email": "johndoe@example.com",
"hobbies": ["reading", "hiking", "coding"]
}
读取JSON数据
在JavaScript中,我们可以使用XMLHttpRequest
对象或fetch
API来异步读取外部的JSON数据。以下是一个使用fetch
API读取JSON数据的示例:
fetch('data.json')
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => {
console.error('Error fetching data:', error);
});
在上面的代码中,我们首先使用fetch('data.json')
方法来获取名为data.json
的JSON文件,然后通过.then(response => response.json())
将响应转换为JSON格式,最后在第二个.then
方法中打印出JSON数据。如果出现错误,会在.catch
中捕获。
示例代码
让我们通过一个实际的示例来演示如何使用JavaScript读取JSON数据。假设我们有一个名为data.json
的JSON文件,内容如下:
{
"books": [
{
"title": "JavaScript: The Good Parts",
"author": "Douglas Crockford",
"publishedYear": 2008
},
{
"title": "Eloquent JavaScript",
"author": "Marijn Haverbeke",
"publishedYear": 2011
},
{
"title": "You Don't Know JS",
"author": "Kyle Simpson",
"publishedYear": 2015
}
]
}
我们的目标是读取该JSON文件并将每本书的信息显示在页面上。以下是完整的HTML和JavaScript代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Reading JSON with JavaScript</title>
</head>
<body>
<h1>Books</h1>
<ul id="bookList"></ul>
<script>
fetch('data.json')
.then(response => response.json())
.then(data => {
const bookList = document.getElementById('bookList');
data.books.forEach(book => {
const li = document.createElement('li');
li.textContent = `{book.title} by{book.author} (${book.publishedYear})`;
bookList.appendChild(li);
});
})
.catch(error => {
console.error('Error fetching data:', error);
});
</script>
</body>
</html>
在上面的代码中,我们首先使用fetch
API获取data.json
文件,然后通过.then(data => {...})
处理返回的JSON数据。在处理数据的回调函数中,我们通过document.createElement
创建li
元素,并将每本书的信息拼接到textContent
中,最后将li
添加到ul
元素中。打开HTML文件,即可看到书籍列表的展示。
运行结果
当我们打开上面的HTML文件时,页面将会展示如下内容:
Books
- JavaScript: The Good Parts by Douglas Crockford (2008)
- Eloquent JavaScript by Marijn Haverbeke (2011)
- You Don’t Know JS by Kyle Simpson (2015)