在javascript中解析具有未知字段名称的json数组

G-J*_*G-J 0 javascript jquery json

我在 StackOverflow 上发现了很多讨论解析 json 数组的线程,但我似乎不知道如何取回一些数据。这是我所拥有的...

    $('#keyword_form').submit(function(e){  
        var gj = $.post('employee_search.php',$('#keyword_form').serialize(),function(data){                
            if(!data || data.status !=1 )
            {
                alert(data.message);
                return false;
            }
            else
            {
                alert(data.message);
            }
        },'json');  
        e.preventDefault();

    });
Run Code Online (Sandbox Code Playgroud)

发送给它的 json 数据看起来像这样......

{
    "status":1,
    "message":"Query executed in 9.946837 seconds.",
    "usernames_count":{
        "gjrowe":5,
        "alisonrowe":4,
        "bob":"1"
    }
}
Run Code Online (Sandbox Code Playgroud)

正如我的函数所示,我可以执行此操作alert(data.message);,但如何访问usernames_count数据?

我的困惑来自于数据没有名称/标签。bob是用户名,1是与该用户名关联的返回计数

如果我这样做alert(usernames_count);我会回来[object Object]

如果我这样做alert(usernames_count[0]);我会回来undefined

我确信我应该做点什么,JSON.parse();但我还没有做对

ZER*_*ER0 5

您可以使用Object.keysfor\xe2\x80\xa6in循环 \xe2\x80\x93 请记住在这种情况下使用hasOwnProperty

\n\n
var users = data.usernames_count;\nObject.keys(users).forEach(function(user) {\n    console.log(user, users[user]);\n});\n
Run Code Online (Sandbox Code Playgroud)\n