pedalpete
pedalpete

Reputation: 21566

get key name from json object

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?

Upvotes: 5

Views: 35973

Answers (3)

afifsay
afifsay

Reputation: 51

You can use jQuery each function to iterate.

data=obj.userList
jQuery.each(data, function(key,value){
  var username=value.username;
  var memberSince=value.memberSince;
  ...
}

Upvotes: 5

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196296

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];
        }
}

Upvotes: 7

Dave Ward
Dave Ward

Reputation: 60590

How about changing your object like this:

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

Then, you can index into the userList array more naturally. That's probably more like what your data will eventually look like coming back from a database backend anyway.

Upvotes: 2

Related Questions