javascript怎麼取得json對象

WBOY
發布: 2023-05-29 15:55:09
原創
1774 人瀏覽過

隨著前端技術的不斷發展,JavaScript 已經成為客戶端開發中最常用的語言。而在一些資料互動應用中,JSON(JavaScript Object Notation)已成為資料傳輸中最常用的格式之一。在 JavaScript 中,取得 JSON 物件是非常常見的操作。

本文將會介紹開發者在 JavaScript 中如何取得 JSON 物件。

  1. 取得 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);
})
登入後複製
  1. 把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}
登入後複製
  1. 取得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'
登入後複製
  1. 實戰應用:取得京東商品資訊

以上對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">&yen;</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">&yen;</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 物件有更好的了解,同時也能運用在實際專案中。

以上是javascript怎麼取得json對象的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!