简体   繁体   English

从JSON数据调用值时使用fetch()并获取“未定义”

[英]Using fetch() and getting 'Undefined' when calling a value from the JSON data

I am able to console.log the JSON response from fetch() and it shows that I am in fact receiving the JSON response from the API URL. 我能够console.log从fetch()获得JSON响应,它表明我实际上是从API URL接收到JSON响应。

This is the code that will console.log the JSON response without an issue (please note that I've ommited res.render() from this code while I am sorting the JSON issue): 这是将在没有问题的情况下console.log JSON响应的代码(请注意,在我对JSON问题进行排序时,我从此代码中省略了res.render()):

app.get('/', function(req, res, next){
    fetch(url)
    .then(function(res){
        return res.json();
    })
    .then(function(data){
        ico = JSON.stringify(data);
        console.log(ico); // Logs the JSON data without issue
    })
    .catch(function(error){
        console.log(error);
    })
});

This is a snippet of that JSON response from the requested URL: 这是来自请求的URL的JSON响应的摘录:

    {
       "ico": {
          "live": [{
             "name": "ViMarket",
             "image": "https://icowatchlist.com/logos/vimarket.png",
             "description": "A 3D marketplace that allows users to create and share virtual reality VR experiences ViMarket promises to bring about a muchneeded breakthrough in the global ecommerce ecosystem",
             "website_link": "https://api.icowatchlist.com/public/v1/url/vimarket",
             "icowatchlist_url": "https://icowatchlist.com/ico/vimarket",
             "start_time": "2017-12-07 00:00:00",
             "end_time": "2018-01-31 00:00:00",
             "timezone": "UTC+0"
          }, {

         "name": "Pocketinns",
         "image": "https://icowatchlist.com/logos/pocketinns.png",
         "description": "The worlds first decentralized blockchain driven marketplace ecosystem",
         "website_link": "https://api.icowatchlist.com/public/v1/url/pocketinns",
         "icowatchlist_url": "https://icowatchlist.com/ico/pocketinns",
         "start_time": "2018-01-15 10:00:00",
         "end_time": "2018-01-31 10:00:00",
         "timezone": "UTC--3"
      }]}
}

My issue began when I was started having a problem using the JSON data that I passed into an EJS template, so I tried to console.log a key-value pair from the JSON data to see to see if there was an issue with it. 我的问题开始于我开始使用传递到EJS模板的JSON数据时遇到问题,因此我尝试从JSON数据进行console.log键值对的记录,以查看是否存在问题。 This showed me that I was getting an 'undefined' value anytime I wanted to call a key-value pair. 这表明我想调用键值对时就得到了“未定义”值。

Here is the code snippet that produces that issue: 这是产生该问题的代码片段:

app.get('/', function(req, res, next){
    fetch(url)
    .then(function(res){
        return res.json();
    })
    .then(function(data){
        let ico = JSON.stringify(data);
        console.log(ico.live.name); // Returns 'undefined'
    })
    .catch(function(error){
        console.log(error);
    })
});

I am confused as to why it will output anything other than 'undefined' when I specifically call a value. 当我专门调用一个值时,为什么它会输出除“ undefined”以外的任何内容,我对此感到困惑。 I am sure there is something I am not doing correctly. 我确定有些事情我做得不正确。

Here is the full snippet: 这是完整的代码段:

app.get('/', function(req, res, next){
        fetch(url)
        .then(function(res){
            return res.json();
        })
        .then(function(data){
            let ico = JSON.stringify(data);
            res.render('pages/index', { ico: ico });
        })
        .catch(function(error){
            console.log(error);
        })
    });

Why can I console.log(ico) and get the entire JSON response without issue, but when I want to console.log(ico.live.name) , I get 'undefined'? 为什么我可以console.log(ico)并获得整个JSON响应而没有问题,但是当我想要console.log(ico.live.name) ,却得到了“ undefined”? From what I can tell from my console.log s, I am passing the entire JSON response into my EJS template, but I am failing to properly access the values in the JSON response from the Javascript in my EJS template. console.log可以看出,我正在将整个JSON响应传递到我的EJS模板中,但是我无法从EJS模板中的Javascript正确访问JSON响应中的值。

If you want to use the properties of the object, don't stringify the data. 如果要使用对象的属性,请不要对数据进行字符串化。

.then(function(ico){
    //let ico = JSON.stringify(data);
    console.log(ico.live.name); 
    // you can then assign the properties to variables and
    // use them
    let liveName = ico.live.name;
    // or, if you need that as a string, use stringify
    let name = JSON.stringify(ico.name);
});

You're unnecessarily transforming the JSON data to a JavaScript Object and then back to JSON text format again, trying to reference Object properties on it. 您不必要地将JSON数据转换为JavaScript对象,然后再次转换为JSON文本格式,从而尝试引用其上的Object属性。

The return res.json() already transforms the JSON response to a JavaScript object, so you should remove your JSON.stringify if you want to access that data. return res.json()已经将JSON响应转换为JavaScript对象,因此,如果要访问该数据,则应删除JSON.stringify

app.get('/', (req, res, next) => {
  fetch(url)
  .then(res => res.json())
  .then(data => res.render('pages/index', { ico: data.ico }))
  .catch(err => {
    console.log(err);
    res.sendStatus(500); // Make sure you close the connection on an error!
  })
});

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

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