简体   繁体   English

已知JSON对象非空值的字段返回空字符串

[英]Fields with known non-empty values of JSON object return empty string

I have an object containing share counts for various social metrics. 我有一个对象,其中包含各种社交指标的份额计数。 The object looks like this: 该对象如下所示:

Object{
delicious: 0,
facebook: {
    comments: 0,
    likes: 0,
    shares: 0,
    total: 0,
},
linkedIn: 1,
pinterest: 0,
twitter: 9
}

Here is some testing code I am using to try to access my object: 这是一些我用来尝试访问对象的测试代码:

    console.log(bg.results);
    console.log(bg.results["facebook"]);
    console.log(bg.results.facebook);

Object.keys(bg.results).forEach(function(key){
    console.log(bg.results);
    console.log(key + "->" + bg.results[key]);
});

The object above is what I am seeing in the console, so I know that the fields in bg.results contain data. 上面的对象就是我在控制台中看到的内容,因此我知道bg.results中的字段包含数据。 The problem is, when I try to access any of these fields using either dot syntax or by using object["key"] I get an empty string as the result. 问题是,当我尝试使用点语法或使用object [“ key”]访问任何这些字段时,都会得到一个空字符串。 I searched and could not find anyone else experiencing the same problem. 我搜索了,找不到其他遇到相同问题的人。 Does anyone have any ideas why this may be happening? 有谁知道为什么会这样?

Some additional info: My code is being run within the context of a chrome extension. 一些其他信息:我的代码正在chrome扩展程序的上下文中运行。 I'm accessing this object from a popup page, and the object's data is being supplied from my background page. 我正在从弹出页面访问该对象,并且该对象的数据是从我的后台页面提供的。

Thank you for your assistance. 谢谢您的帮助。

UPDATE 更新

Something funny is going on with how Chrome is handling my code. Chrome处理我的代码的方式正在发生一些有趣的事情。 The data in bg.results is supplied by a function on my background page called update. bg.results中的数据由我的后台页面上的一个称为update的函数提供。 In my program there are two ways that update is called depending on the user's settings. 在我的程序中,根据用户的设置,有两种调用更新的方法。 When update() is called from within the context of my background page, everything works fine and behaves as expected. 当从我的后台页面的上下文中调用update()时,一切工作正常,并且行为正常。 When update() is called from my popup page, I get empty strings when I try to access any fields. 当从弹出页面中调用update()时,尝试访问任何字段时都会得到空字符串。

This seems like a bug very particular to how chrome extensions are handled, so any input from experts in this sort of thing would be awesome. 对于Chrome扩展程序的处理方式,这似乎是一个非常特殊的错误,因此专家在此类事情上的任何投入都将是很棒的。 Thanks for the help everyone! 感谢大家的帮助!

1.) your code should work. 1.)您的代码应该工作。 facebook is an object itself so you need to think about that, and maybe use a recursive function! facebook本身就是一个对象,因此您需要考虑一下,也许可以使用递归函数!

2.) why dont you just loop over your objects properties with the for-in-loop? 2.)为什么不只使用for-in-loop遍历对象属性?

for(key in bg.results) {
   console.log(key);
}

3.) example recursive function 3.)递归函数示例

function recursiveExample(obj) {
  var current;
  for(key in obj) {
   current = obj[key];
   if(typeof current === 'object' && !Array.isArray(current)) {
     recursiveExample(current);  
   }
   console.log("key: " + key + " - value" + current);
  }
}

I've concluded that my values were not completely loaded into the results object when I was trying to access them. 我得出的结论是,当我尝试访问它们时,我的值没有完全加载到结果对象中。 I can only speculate as to why I could see the values when I printed the results object to the console (and could not access them at that point) but was not able to access them until later. 我只能推测为什么在将结果对象打印到控制台时可以看到这些值(当时无法访问它们),但是直到以后才能访问它们。 Below is the solution I used for this problem. 以下是我用于此问题的解决方案。

function checkLoaded(results){
    var isLoaded = true;
    $.each(results, function(key, value){
        if(value === "" || value === undefined){
            isLoaded = false;   
        }
    });

    setTimeout(function(){
         if(!isLoaded){
            checkLoaded(results);
         }
         else{
            displayHandler(results);
         }
    }, 500);

}

If anyone knows why I could see the values in the console but could not access them, I'd appreciate an explanation. 如果有人知道为什么我可以在控制台中看到这些值却无法访问它们,那么我将不胜感激。 But otherwise, if anyone else encounters a problem like this, try setting up a delay to make sure that your values are completely loaded into your collection. 但是否则,如果其他任何人遇到这样的问题,请尝试设置延迟以确保将值完全加载到集合中。

This is just a guess (since you haven't posted any of the relevant data-loading code), but I suspect you may be doing something like this: 这只是一个猜测(因为您尚未发布任何相关的数据加载代码),但是我怀疑您可能正在执行以下操作:

chrome.extension.sendMessage({myAction: "update"}, function(response) {
     bg.results = response;
});

// we try to use bg.results, but the sendMessage callback won't be run until later on
Object.keys(bg.results).forEach(function(key){
    console.log(bg.results);
    console.log(key + "->" + bg.results[key]);
});

The ansychronous callback passed to sendMessage runs after the current function stack has cleared (ie, once the JavaScript thread has run out of other things to do), so bg.results = response won't happen until after you try to use it. 传递给sendMessage的异步回调将清除当前函数堆栈运行(即,一旦JavaScript线程用尽了其他事情要做),因此bg.results = response在您尝试使用它之后才会发生。 Instead, use the results inside the callback : 而是在回调中使用结果:

chrome.extension.sendMessage({myAction: "update"}, function(response) {
     bg.results = response;

    // now it works, because this code is inside the callback
    Object.keys(bg.results).forEach(function(key){
        console.log(bg.results);
        console.log(key + "->" + bg.results[key]);
    });
});

Maybe you don't actually use chrome.extension.sendMessage , but you must be using some asynchronous operation (maybe Ajax, maybe another Chrome API call). 也许您实际上并没有使用chrome.extension.sendMessage ,但是您必须使用一些异步操作(也许是Ajax,也许是另一个Chrome API调用)。 I don't know what that method is for certain, since you didn't post any of your data-loading code. 我不知道该方法肯定是什么,因为您没有发布任何数据加载代码。

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

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