json怎么解析

JS

1个回答

写回答

Rccha

2022-04-26 15:08

+ 关注

JS
JS

1. 使用JSON.parse()方法将JSON字符串转化为Javascript对象。

JS

const JSonString = '{"name": "Tom", "age": 25}';

Java
Java

const JSonObj = JSON.parse(JSonString);

console.log(JSonObj.name); // Tom

console.log(JSonObj.age); // 25

2. 使用JSON.stringify()方法将Javascript对象转化为JSON字符串。

JS

const JSonObj = {name: "Tom", age: 25};

const JSonString = JSON.stringify(JSonObj);

console.log(JSonString); // {"name":"Tom","age":25}

3. 使用XMLHttpRequest获取JSON数据并解析。

JS

const xhr = new XMLHttpRequest();

xhr.open('GET', 'url/to/JSon', true);

xhr.onreadystatechange = function() {

if (xhr.readyState === XMLHttpRequest.DONE) {

if (xhr.status === 200) {

const JSonResponse = JSON.parse(xhr.responseText);

console.log(JSonResponse);

} else {

console.log('Error: ' + xhr.statusText);

}

}

};

xhr.send();

4.使用fetch方法获取JSON数据并解析。

JS

fetch('url/to/JSon')

.then(response => response.JSon())

.then(data => {

console.log(data);

})

.catch(error => {

console.log('Error: ' + error);

});

举报有用(17分享收藏

Copyright © 2025 IZhiDa.com All Rights Reserved.

知答 版权所有 粤ICP备2023042255号