Home Web Front-end Front-end Q&A How to get json object in javascript

How to get json object in javascript

May 29, 2023 pm 03:55 PM

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);
})
Copy after login
  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}
Copy after login
  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'
Copy after login
  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);
})
Copy after login

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);
})
Copy after login

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);
})
Copy after login

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>
Copy after login

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How do you connect React components to the Redux store using connect()? How do you connect React components to the Redux store using connect()? Mar 21, 2025 pm 06:23 PM

Article discusses connecting React components to Redux store using connect(), explaining mapStateToProps, mapDispatchToProps, and performance impacts.

React's Role in HTML: Enhancing User Experience React's Role in HTML: Enhancing User Experience Apr 09, 2025 am 12:11 AM

React combines JSX and HTML to improve user experience. 1) JSX embeds HTML to make development more intuitive. 2) The virtual DOM mechanism optimizes performance and reduces DOM operations. 3) Component-based management UI to improve maintainability. 4) State management and event processing enhance interactivity.

How do you define routes using the <Route> component? How do you define routes using the <Route> component? Mar 21, 2025 am 11:47 AM

The article discusses defining routes in React Router using the &lt;Route&gt; component, covering props like path, component, render, children, exact, and nested routing.

What are the limitations of Vue 2's reactivity system with regard to array and object changes? What are the limitations of Vue 2's reactivity system with regard to array and object changes? Mar 25, 2025 pm 02:07 PM

Vue 2's reactivity system struggles with direct array index setting, length modification, and object property addition/deletion. Developers can use Vue's mutation methods and Vue.set() to ensure reactivity.

What are Redux reducers? How do they update the state? What are Redux reducers? How do they update the state? Mar 21, 2025 pm 06:21 PM

Redux reducers are pure functions that update the application's state based on actions, ensuring predictability and immutability.

What are the benefits of using TypeScript with React? What are the benefits of using TypeScript with React? Mar 27, 2025 pm 05:43 PM

TypeScript enhances React development by providing type safety, improving code quality, and offering better IDE support, thus reducing errors and improving maintainability.

What are Redux actions? How do you dispatch them? What are Redux actions? How do you dispatch them? Mar 21, 2025 pm 06:21 PM

The article discusses Redux actions, their structure, and dispatching methods, including asynchronous actions using Redux Thunk. It emphasizes best practices for managing action types to maintain scalable and maintainable applications.

How can you use useReducer for complex state management? How can you use useReducer for complex state management? Mar 26, 2025 pm 06:29 PM

The article explains using useReducer for complex state management in React, detailing its benefits over useState and how to integrate it with useEffect for side effects.

See all articles