搜尋
首頁web前端前端問答javascript怎麼取得json對象

隨著前端技術的不斷發展,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 id="">(.*?)</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="/static/imghwm/default1.png"  data-src="//img.*?s(.*?)"  class="lazy"/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 id="">(.*?)</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="/static/imghwm/default1.png"  data-src="//img.*?s(.*?)"  class="lazy"/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中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
了解usestate():綜合反應國家管理指南了解usestate():綜合反應國家管理指南Apr 25, 2025 am 12:21 AM

useState()isaReacthookusedtomanagestateinfunctionalcomponents.1)Itinitializesandupdatesstate,2)shouldbecalledatthetoplevelofcomponents,3)canleadto'stalestate'ifnotusedcorrectly,and4)performancecanbeoptimizedusinguseCallbackandproperstateupdates.

使用React的優點是什麼?使用React的優點是什麼?Apr 25, 2025 am 12:16 AM

ReactispupularduetoItsOmpontement,基於虛擬,虛擬詞,Richecosystem和declarativedation.1)基於組件的harchitectureallowslowsforreusableuipieces。

在React中調試:識別和解決共同問題在React中調試:識別和解決共同問題Apr 25, 2025 am 12:09 AM

todebugreactapplicationsefectefectionfection,usethestertate:1)proppropdrillingwithcontextapiorredux.2)使用babortControllerToptopRollerTopRollerTopRollerTopRollerTopRollerTopRollerTopRollerTopRollerTopRollerTopRaceeDitions.3)intleleassynChronOusOperations.3)

反應中的usestate()是什麼?反應中的usestate()是什麼?Apr 25, 2025 am 12:08 AM

usestate()inrectallowsStateMagementionInfunctionalComponents.1)ITSIMPLIFIESSTATEMAGEMENT,MACHECODEMORECONCONCISE.2)usetheprevcountfunctionToupdateStateBasedonitspReviousViousViousvalue,deveingingStaleStateissues.3)

usestate()與用戶ducer():為您的狀態需求選擇正確的掛鉤usestate()與用戶ducer():為您的狀態需求選擇正確的掛鉤Apr 24, 2025 pm 05:13 PM

selectUsestate()forsimple,獨立的variables; useusereducer()forcomplexstateLogicorWhenStatedIppedsonPreviousState.1)usestate()isidealForsImpleupDatesLikeToggGlikGlingaBglingAboolAboolAupDatingacount.2

使用usestate()管理狀態:實用教程使用usestate()管理狀態:實用教程Apr 24, 2025 pm 05:05 PM

useState優於類組件和其它狀態管理方案,因為它簡化了狀態管理,使代碼更清晰、更易讀,並與React的聲明性本質一致。 1)useState允許在函數組件中直接聲明狀態變量,2)它通過鉤子機制在重新渲染間記住狀態,3)使用useState可以利用React的優化如備忘錄化,提升性能,4)但需注意只能在組件頂層或自定義鉤子中調用,避免在循環、條件或嵌套函數中使用。

何時使用usestate()以及何時考慮替代狀態管理解決方案何時使用usestate()以及何時考慮替代狀態管理解決方案Apr 24, 2025 pm 04:49 PM

useUsestate()forlocalComponentStateMangementighatighation; 1)usestate()isidealforsimple,localforsimple.2)useglobalstate.2)useglobalstateSolutionsLikErcontExtforsharedState.3)

React的可重複使用的組件:增強代碼可維護性和效率React的可重複使用的組件:增強代碼可維護性和效率Apr 24, 2025 pm 04:45 PM

ReusableComponentsInrectenHanceCodainainability and效率byallowingDevelostEsteSeTheseTheseThesAmeCompOntionActActRossDifferentPartSofanApplicationorprojects.1)heSredunceRedUndenceNandSimplifyUpdates.2)yensureconsistencyInuserexperience.3)

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器