How to get json object in javascript

WBOY
Release: 2023-05-29 15:55:09
Original
1754 people have browsed it

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 = /
s*

(.*?)

/gi; const regPrice = /s*¥/gi; const regImg = / { 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 = /
s*

(.*?)

/gi; const regPrice = /s*¥/gi; const regImg = / { 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.

    Get Product Info 
  
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!

source:php.cn
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!