简体   繁体   English

从REST API调用解析JSON响应

[英]Parsing JSON response from a REST API call

I'm quite new to using APIs. 我对使用API​​很陌生。

I am trying to take the response Text and sort info from it into different areas of a card. 我正在尝试获取响应文本并将其中的信息分类到卡的不同区域。 I'm not asking for a quick answer, but rather some documentation that I can go over to get a full understanding. 我不是在寻求快速解答,而是要阅读一些文档以得到全面的了解。

 var stat = document.getElementById('infoboxName'); var promise1 = new Promise(function(resolve, reject) { setTimeout(function() { var xhr = new XMLHttpRequest(), method = "GET", url = "https://www.anapioficeandfire.com/api/characters/124"; xhr.open(method, url, true); xhr.onreadystatechange = function() { if (xhr.readyState === 4 && xhr.status === 200) { console.log(xhr.responseText); stat.innerHTML = xhr.responseText; resolve("resolve"); } }; xhr.send(); }, 300); }); promise1.then(function(value) { console.log(value); }); 
 <div id='infoboxName'></div> 

response output 响应输出

{
  "url": "https://www.anapioficeandfire.com/api/characters/124",
  "name": "Antario Jast",
  "gender": "Male",
  "culture": "",
  "born": "",
  "died": "",
  "titles": [
    "Lord"
  ],
  "aliases": [
    ""
  ],
  "father": "",
  "mother": "",
  "spouse": "https://www.anapioficeandfire.com/api/characters/616",
  "allegiances": [
    "https://www.anapioficeandfire.com/api/houses/212"
  ],
  "books": [
    "https://www.anapioficeandfire.com/api/books/2",
    "https://www.anapioficeandfire.com/api/books/3",
    "https://www.anapioficeandfire.com/api/books/5",
    "https://www.anapioficeandfire.com/api/books/8"
  ],
  "povBooks": [],
  "tvSeries": [
    ""
  ],
  "playedBy": [
    ""
  ]
}

What you really want to do is parse that response, for doing that you can use JSON.parse which converts a JSON string into a JS Object. 您真正想做的是解析该响应,为此,您可以使用JSON.parse将JSON字符串转换为JS对象。

After parsing that JSON string, you can access the data using the specific properties like name and gender . 解析该JSON字符串后,您可以使用特定的属性(例如namegender访问数据。

On the other hand, I think you don't need that setTimeout at all. 另一方面,我认为您根本不需要setTimeout

This example parses the JSON string and gets the name and gender , likewise through the function resolve I'm passing the parsed JSON string as JS Object. 这个示例解析JSON字符串并获取namegender ,同样通过函数resolve我将解析的JSON字符串作为JS对象传递。

 var nameElement = document.getElementById('name'); var genderElement = document.getElementById('gender'); var promise1 = new Promise(function(resolve, reject) { var xhr = new XMLHttpRequest(), method = "GET", url = "https://www.anapioficeandfire.com/api/characters/124"; xhr.open(method, url, true); xhr.onreadystatechange = function() { if (xhr.readyState === 4 && xhr.status === 200) { resolve(JSON.parse(xhr.responseText)); } }; xhr.send(); }); promise1.then(function(value) { nameElement.textContent = value.name; genderElement.textContent = value.gender; }); 
 <div id='infoboxName'> <span id='name'></span> <p/> <span id='gender'></span> </div> 

It's a good thing that you're getting familiar with XMLHttpRequest , but for the sake of simplicity it's probably a good idea to start with a simpler syntax: 熟悉XMLHttpRequest是一件好事,但是为了简单起见,以更简单的语法开始可能是个好主意:

var stat = document.getElementById('infoboxName');
var apiResponse = await fetch("https://www.anapioficeandfire.com/api/characters/124");
var jsonParsedContents = await apiResponse.json(); // This is also a promise so must also wait for it

console.log(jsonParsedContents); // Do whatever you need with the object

If for some reason you cannot use fetch and must stick to XMLHttpRequest , then it's the value passed in your call to resolve you want to change: 如果由于某种原因您不能使用fetch并且必须坚持使用XMLHttpRequest ,那么它是您在调用中传递的用于resolve您想要更改的值:

var stat = document.getElementById('infoboxName');
var promise1 = new Promise(function(resolve, reject) {
    var xhr = new XMLHttpRequest(),
        method = "GET",
        url = "https://www.anapioficeandfire.com/api/characters/124";

    xhr.open(method, url, true);
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4 && xhr.status === 200) {
            resolve(JSON.parse(xhr.responseText));
        }
    };
    xhr.send();
});

promise1.then(function(result) {
    console.log(result);
    // In here you'll probably want to stat.innerHTML = <some part of result>
});

In the code above I'm also assuming you want the promise to be handled in a different piece of code from where the API request is being sent, but if not, then you don't need that either and can simply do what you need with the response inside your if . 在上面的代码中,我还假设您希望将承诺与发送API请求的地方放在不同的代码中进行处理,但是如果没有,那么您也不需要这样做,并且可以简单地执行所需的操作if内有响应。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM