qqruza
qqruza

Reputation: 1417

Get the key name from JSON

I have got a JSON string:

 var json = {
"result": [{
    "ID": "9",
    "user_name": "Mr Smith",
"authormeta": {
    "session_token": {
    "5633543626268661e7": {
            "expiration": 1423329065
        }
    }
}
}]
}

 $('p').append(json.result[0].ID + ' | ' + json.result[0].user_name + ' | ' + json.result[0].authormeta.session_tokens + ' | ' + json.result[0].authormeta.session_tokens.expiration);

And successfully getting json.result[0].ID + json.result[0].user_name but having a problem of getting dynamically changed key name - json.result[0].authormeta.session_tokens and value of the expiration.

It should look like in html: 9 | Mr Smith | 5633543626268661e7 | 1423329065

My demo JSFIDDLE is here http://jsfiddle.net/gegjsb6w/2/

Can any body please help me to amend the JSFIDDLE to get the info I need. Thank you in advance.

Upvotes: 2

Views: 73

Answers (1)

Oleksandr T.
Oleksandr T.

Reputation: 77482

Try this,

var sessionKey = Object.keys(json.result[0].authormeta.session_token).pop(),
    session    = json.result[0].authormeta.session_token[sessionKey];

$('p').append(json.result[0].ID + ' ' + json.result[0].user_name + sessionKey + ' ' + session.expiration);
  1. In JSON Object there is session_token but no session_tokens.
  2. To get properties expiration and login you need to get key ("5633543626268661e7") you can get it dynamically using Object.keys (As in my example)

Example

Upvotes: 1

Related Questions