Home  >  Article  >  Web Front-end  >  How to get json object in javascript

How to get json object in javascript

WBOY
WBOYOriginal
2023-05-29 15:55:091843browse

With the continuous development of front-end technology, JavaScript has become the most commonly used language in client development. In some data interaction applications, JSON (JavaScript Object Notation) has become one of the most commonly used formats for data transmission. In JavaScript, getting a JSON object is a very common operation.

This article will introduce how developers obtain JSON objects in JavaScript.

  1. Get JSON string

First of all, the first step to get the JSON object is to get the JSON string. In JavaScript, you can get a JSON string in many ways, such as getting it from the server, making an Ajax request, reading from a local file, etc.

The method of obtaining the JSON string is as follows:

// 通过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. Convert the JSON string to a JSON object

After obtaining the JSON string, The next step is to convert the JSON string into a JSON object. In JavaScript, you can use the JSON.parse() method to convert a JSON string into a JSON object.

The method is as follows:

const jsonStr = '{"name": "Alice", "age": 18}';
const jsonObj = JSON.parse(jsonStr);
console.log(jsonObj); // 输出:{name: "Alice", age: 18}
  1. Get the value in the JSON object

There are two ways to get the value in the JSON object: dot operator and square brackets. For nested JSON objects, you can also use a combination of dot or bracket operators to access nested properties.

As shown below:

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. Practical application: Obtaining JD product information

The above introduction to JSON objects is based on theoretical explanations. The following will help developers better understand and apply it through practical applications.

This application will be implemented by obtaining product information from the JD website. The following are the main steps to obtain JD product information:

  • Get the page HTML of the specified product
  • Parse the HTML code and obtain the product information data
  • Convert the product information data For JSON objects
  • Display product information through JSON objects

First, you need to obtain the HTML code of the product page. In JavaScript, the JD product page HTML can be obtained through Ajax.

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);
})

Next, you need to use regular expressions to parse the HTML code to obtain product information data.

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);
})

Since product information data is structured data, it is best to convert it into a JSON object.

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);
})

Finally, the product information JSON object can be displayed through the front-end page.

<!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

Obtaining JSON objects in JavaScript is a relatively basic skill and one of the necessary skills for front-end development. Through studying this article, I hope readers will have a better understanding of how to obtain JSON objects in JavaScript, and can also apply it in actual projects.

The above is the detailed content of How to get json object in javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:center cssNext article:center css