Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get key name from json object

Tags:

json

jquery

key

This is almost exactly the same as this question json get key names as text?, but that response isn't working for me.

I've got a json object

{"userList":[
{"user1":[{"username":"mike","memberSince":"01/03/2011"}]},
{"user2":[{"username":"john","memberSince":"01/05/2011"}]},
]}

The only reason I have a the "user1" and "user2" labels is because I'm storing the userlist by userId in jQuery data, and then stringifying it to put it in a cookie and send it in another page. I know, sounds stupid, but I'm just building some front end stuff to prove a point before doing this properly with a db.

So the

jQuery('div#userList').data('user1',user1JSON);

turns into

{"user1":[{"username":"mike","memberSince":"01/03/2011"}]}

when using

var userlist=JSON.stringify(jQuery('div#userList').data());

Because of this, the user info is now a child of the userId, instead of just being a child of userlist.

In order to get the user info, I should be able to say

for(u=0;u<userList.length;u++){
   var userInfo=userList[u][0];
}

but unfortunately this is just giving me an undefined error. If I use

var userInfo = userList[u]['user1'];

I get the user info correctly.

So, can somebody correct me as to why userList[u][0] does not work, OR

explain to me how to use JSON.stringify without adding the userid to the beginning of the string?

like image 495
pedalpete Avatar asked Jan 10 '11 23:01

pedalpete


1 Answers

That is because the userList[u] returns an object, not an array.

And you cannot access the object properties with an index..

you could try

for(u=0;u<userList.length;u++){
   for (var user in userList[u])
        {
          // user is the key
          // userList[u][user] is the value
          var userInfo=userList[u][user];
        }
}
like image 112
Gabriele Petrioli Avatar answered Sep 28 '22 00:09

Gabriele Petrioli