0

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"
  }
}
Shreevardhan
  • 12,233
  • 3
  • 36
  • 50
Ahsan Abbas
  • 73
  • 1
  • 8

4 Answers4

1

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;
Clive Seebregts
  • 2,004
  • 14
  • 18
0

simply try

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

similarly you can access values of other attributes in the obj

gurvinder372
  • 66,980
  • 10
  • 72
  • 94
0

You can also access the contents via:

var token = obj["token"];

or

var username = obj["user"]["username"];
MerlinK
  • 526
  • 6
  • 9
0

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];
 }
}
Markus Guder
  • 621
  • 1
  • 5
  • 11