자바스크립트에서 json 객체를 얻는 방법

WBOY
풀어 주다: 2023-05-29 15:55:09
원래의
1779명이 탐색했습니다.

프론트 엔드 기술의 지속적인 발전으로 JavaScript는 클라이언트 개발에서 가장 일반적으로 사용되는 언어가 되었습니다. 일부 데이터 상호 작용 애플리케이션에서 JSON(JavaScript Object Notation)은 데이터 전송에 가장 일반적으로 사용되는 형식 중 하나가 되었습니다. JavaScript에서 JSON 개체를 가져오는 것은 매우 일반적인 작업입니다.

이 글에서는 개발자가 JavaScript에서 JSON 개체를 얻는 방법을 소개합니다.

  1. JSON 문자열 가져오기

먼저 JSON 개체를 가져오는 첫 번째 단계는 JSON 문자열을 가져오는 것입니다. JavaScript에서는 서버에서 가져오기, Ajax 요청 만들기, 로컬 파일에서 읽기 등 다양한 방법으로 JSON 문자열을 가져올 수 있습니다.

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. 실용 적용: JD 제품 정보 얻기

위의 JSON 개체 소개는 이론적 설명을 기반으로 합니다. 다음으로, 개발자가 더 잘 이해하고 적용할 수 있도록 실제 적용을 사용합니다.

본 어플리케이션은 JD 홈페이지에서 상품정보를 얻어 구현됩니다. 다음은 JD.com 제품 정보를 얻는 주요 단계입니다.

  • 특정 제품의 페이지 HTML 가져오기
  • HTML 코드 구문 분석 및 제품 정보 데이터 가져오기
  • 제품 정보 데이터를 JSON 개체로 변환
  • JSON 개체를 통해 제품 정보 표시

먼저 제품 페이지의 HTML 코드를 가져와야 합니다. JavaScript에서는 Ajax를 통해 JD 제품 페이지 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>
로그인 후 복사

Summary

JavaScript에서 JSON 객체를 얻는 것은 상대적으로 기본적인 기술이자 프런트엔드 개발에 필요한 기술 중 하나입니다. 이 글을 통해 독자들이 JavaScript에서 JSON 객체를 얻는 방법을 더 잘 이해하고 실제 프로젝트에 적용할 수 있기를 바랍니다.

위 내용은 자바스크립트에서 json 객체를 얻는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!