随着前端技术的不断发展,JavaScript 已经成为客户端开发中最常用的语言。而在一些数据交互应用中,JSON(JavaScript Object Notation)已经成为数据传输中最常用的格式之一。在 JavaScript 中,获取 JSON 对象是非常常见的操作。
本文将会介绍开发者在 JavaScript 中如何获取 JSON 对象。
- 获取 JSON 字符串
首先,获取 JSON 对象的第一步就是获取 JSON 字符串。在 JavaScript 中,可以通过多种方式获取 JSON 字符串,比如从服务器端获取、通过 Ajax 请求、从本地文件读取等方式。
获取 JSON 字符串的方法如下所示:
// 通过Ajax获取JSON字符串
const xhr = new XMLHttpRequest();
xhr.open('GET', 'json/data.json', true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status ===200) {
const jsonStr = xhr.responseText;
console.log(jsonStr);
}
}
xhr.send();
// 从JS对象中获取JSON字符串
const obj = {name: 'Alice', age: 18};
const jsonStr = JSON.stringify(obj);
console.log(jsonStr);
// 从本地文件读取JSON字符串
fetch('data.json')
.then(response => response.json())
.then(data => {
const jsonStr = JSON.stringify(data);
console.log(jsonStr);
})
.catch(err => {
console.log('Error: ', err);
})- 把 JSON 字符串转换为 JSON 对象
获取了 JSON 字符串之后,下一步就是把 JSON 字符串转换为 JSON 对象。在 JavaScript 中,可以使用 JSON.parse() 方法将 JSON 字符串转换为 JSON 对象。
方法如下:
const jsonStr = '{"name": "Alice", "age": 18}';
const jsonObj = JSON.parse(jsonStr);
console.log(jsonObj); // 输出:{name: "Alice", age: 18}- 获取 JSON 对象中的值
获取 JSON 对象中的值有两种方式:点运算符和方括号。对于嵌套的 JSON 对象,还可以使用点或方括号运算符的组合来访问嵌套的属性。
如下所示:
const jsonObj = {name: 'Alice', age: 18, address: {city: 'Shanghai', street: 'Nanjing Road'}};
// 通过点运算符访问JSON对象属性
console.log(jsonObj.name); // 输出:'Alice'
// 通过方括号运算符访问JSON对象属性
console.log(jsonObj['age']); // 输出:18
// 访问嵌套JSON对象中的属性
console.log(jsonObj.address.city); // 输出:'Shanghai'
console.log(jsonObj['address']['street']); // 输出:'Nanjing Road'- 实战应用:获取京东商品信息
以上对 JSON 对象的介绍都是基于理论的讲解,接下来将会通过实战应用帮助开发者更好地理解和应用。
本应用将会通过从京东网站中获取商品信息来实现。下面是获取京东商品信息的主要步骤:
- 获取指定商品的页面 HTML
- 解析 HTML 代码,获取商品信息数据
- 将商品信息数据转换为 JSON 对象
- 通过 JSON 对象展示商品信息
首先,需要获取商品页面的 HTML 代码。在 JavaScript 中,可以通过 Ajax 的方式获取京东商品页面 HTML。
function getHtml(url) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status >=200 && xhr.status <300 || xhr.status === 304) {
resolve(xhr.responseText);
} else {
reject(new Error(xhr.status));
}
}
}
xhr.send();
});
}
getHtml('https://item.jd.com/10024311244369.html')
.then(html => {
console.log(html)
})
.catch(err => {
console.log('Error: ', err);
})接着,需要使用正则表达式解析 HTML 代码,获取商品信息数据。
function parseHtml(html) {
const regName = /<div class="sku-name">s*<h1>(.*?)</h1>/gi;
const regPrice = /<span class="p-price">s*<span class="price-symbol">¥</span><strong class="price J-p-d+" data-price="(.*?)">/gi;
const regImg = /<img src="//img.*?s(.*?)"/gi;
const name = regName.exec(html)[1];
const price = regPrice.exec(html)[1];
const img = 'https:' + regImg.exec(html)[1];
return {name, price, img};
}
getHtml('https://item.jd.com/10024311244369.html')
.then(html => {
const data = parseHtml(html);
console.log(data);
})
.catch(err => {
console.log('Error: ', err);
})由于商品信息数据是结构化数据,最好将其转换为 JSON 对象。
function parseHtml(html) {
const regName = /<div class="sku-name">s*<h1>(.*?)</h1>/gi;
const regPrice = /<span class="p-price">s*<span class="price-symbol">¥</span><strong class="price J-p-d+" data-price="(.*?)">/gi;
const regImg = /<img src="//img.*?s(.*?)"/gi;
const name = regName.exec(html)[1];
const price = regPrice.exec(html)[1];
const img = 'https:' + regImg.exec(html)[1];
return {name, price, img};
}
function getJson(url) {
return new Promise((resolve, reject) => {
getHtml(url)
.then(html => {
const data = parseHtml(html);
const json = JSON.stringify(data);
resolve(json);
})
.catch(err => {
reject(err);
})
});
}
getJson('https://item.jd.com/10024311244369.html')
.then(json => {
console.log(json);
})
.catch(err => {
console.log('Error: ', err);
})最后,可以将商品信息 JSON 对象通过前端页面进行展示。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Get Product Info</title>
</head>
<body>
<div id="app"></div>
<script>
function getJson(url) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status >=200 && xhr.status <300 || xhr.status === 304) {
const json = JSON.parse(xhr.responseText);
resolve(json);
} else {
reject(new Error(xhr.status));
}
}
}
xhr.send();
});
}
function render(data) {
const appNode = document.getElementById('app');
const imgNode = document.createElement('img');
const nameNode = document.createElement('h2');
const priceNode = document.createElement('h3');
imgNode.setAttribute('src', data.img);
nameNode.innerText = data.name;
priceNode.innerText = '价格:' + data.price;
appNode.appendChild(imgNode);
appNode.appendChild(nameNode);
appNode.appendChild(priceNode);
}
getJson('https://item.jd.com/10024311244369.html')
.then(json => {
render(json);
})
.catch(err => {
console.log('Error: ', err);
})
</script>
</body>
</html>总结
JavaScript 中获取 JSON 对象是一项比较基础的技能,也是前端开发的必备技能之一。通过本文的学习,希望读者对于 JavaScript 中如何获取 JSON 对象有更好的了解,同时也能够运用在实际项目中。
