Ahsan Abbas
Ahsan Abbas

Reputation: 73

iterating through a json object

I'm having a really hard time trying to find a way to iterate through this JSON object in the way that I'd like. I want to separate the token in a variable and the user details in other variables. I'm using only Javascript here.

First, here's the object

{
  "token": "517b27a84a4d373a636e323a9572a0ab43883291", 
  "user": {
    "credential_id":"1",
    "name":"name",
    "password":"password",
    "age":"25",
    "email":"kalay@peelay.com",
    "img_src":"043008thmy.jpg",
    "user_type":"0",
    "username":"kalay"
  }
}

Upvotes: 0

Views: 70

Answers (4)

Markus Guder
Markus Guder

Reputation: 671

Simply use the key value to iterate, my method is a little bit static, because it requires that you know "token" und "user" exit in your json.

var token = "",
    user = {};

for(var key in jsonObject){
 if(key == "token"){
    token = jsonObject[key];
 }
 if(key == "user"){
    user = jsonObject[key];
 }
}

Upvotes: 0

MerlinK
MerlinK

Reputation: 536

You can also access the contents via:

var token = obj["token"];

or

var username = obj["user"]["username"];

Upvotes: 0

Clive Seebregts
Clive Seebregts

Reputation: 2034

Use JSON.parse which deserializes JSON to produce a JavaScript object or array.

This example uses JSON.parse to deserialize JSON into the json_obj object.

var json_obj = JSON.parse(json);
var token = json_obj.token;
var username = json_obj.user.username;
var email = json_obj.user.email;

Upvotes: 1

gurvinder372
gurvinder372

Reputation: 68433

simply try

var token = obj.token;
var user_credentials = obj.user.credential_id;

similarly you can access values of other attributes in the obj

Upvotes: 0

Related Questions