隨著前端技術(shù)的不斷發(fā)展,javascript 已經(jīng)成為客戶端開發(fā)中最常用的語言。而在一些數(shù)據(jù)交互應(yīng)用中,json(javascript object notation)已經(jīng)成為數(shù)據(jù)傳輸中最常用的格式之一。在 javascript 中,獲取 json 對象是非常常見的操作。
本文將會介紹開發(fā)者在 JavaScript 中如何獲取 JSON 對象。
首先,獲取 JSON 對象的第一步就是獲取 JSON 字符串。在 JavaScript 中,可以通過多種方式獲取 JSON 字符串,比如從服務(wù)器端獲取、通過 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 字符串轉(zhuǎn)換為 JSON 對象。在 JavaScript 中,可以使用 JSON.parse() 方法將 JSON 字符串轉(zhuǎn)換為 JSON 對象。
立即學(xué)習(xí)“Java免費(fèi)學(xué)習(xí)筆記(深入)”;
方法如下:
const jsonStr = '{"name": "Alice", "age": 18}'; const jsonObj = JSON.parse(jsonStr); console.log(jsonObj); // 輸出:{name: "Alice", age: 18}
獲取 JSON 對象中的值有兩種方式:點(diǎn)運(yùn)算符和方括號。對于嵌套的 JSON 對象,還可以使用點(diǎn)或方括號運(yùn)算符的組合來訪問嵌套的屬性。
如下所示:
const jsonObj = {name: 'Alice', age: 18, address: {city: 'Shanghai', street: 'Nanjing Road'}}; // 通過點(diǎn)運(yùn)算符訪問JSON對象屬性 console.log(jsonObj.name); // 輸出:'Alice' // 通過方括號運(yùn)算符訪問JSON對象屬性 console.log(jsonObj['age']); // 輸出:18 // 訪問嵌套JSON對象中的屬性 console.log(jsonObj.address.city); // 輸出:'Shanghai' console.log(jsonObj['address']['street']); // 輸出:'Nanjing Road'
以上對 JSON 對象的介紹都是基于理論的講解,接下來將會通過實(shí)戰(zhàn)應(yīng)用幫助開發(fā)者更好地理解和應(yīng)用。
本應(yīng)用將會通過從京東網(wǎng)站中獲取商品信息來實(shí)現(xiàn)。下面是獲取京東商品信息的主要步驟:
首先,需要獲取商品頁面的 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); })
接著,需要使用正則表達(dá)式解析 HTML 代碼,獲取商品信息數(shù)據(jù)。
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); })
由于商品信息數(shù)據(jù)是結(jié)構(gòu)化數(shù)據(jù),最好將其轉(zhuǎn)換為 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 對象通過前端頁面進(jìn)行展示。
<!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>
總結(jié)
JavaScript 中獲取 JSON 對象是一項(xiàng)比較基礎(chǔ)的技能,也是前端開發(fā)的必備技能之一。通過本文的學(xué)習(xí),希望讀者對于 JavaScript 中如何獲取 JSON 對象有更好的了解,同時也能夠運(yùn)用在實(shí)際項(xiàng)目中。
以上就是javascript怎么獲取json對象的詳細(xì)內(nèi)容,更多請關(guān)注php中文網(wǎng)其它相關(guān)文章!
java怎么學(xué)習(xí)?java怎么入門?java在哪學(xué)?java怎么學(xué)才快?不用擔(dān)心,這里為大家提供了java速學(xué)教程(入門到精通),有需要的小伙伴保存下載就能學(xué)習(xí)啦!
微信掃碼
關(guān)注PHP中文網(wǎng)服務(wù)號
QQ掃碼
加入技術(shù)交流群
Copyright 2014-2025 http://www.miracleart.cn/ All Rights Reserved | php.cn | 湘ICP備2023035733號