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":"[email protected]",
    "img_src":"043008thmy.jpg",
    "user_type":"0",
    "username":"kalay"
  }
}
2

4 Answers 4

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;
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

You can also access the contents via:

var token = obj["token"];

or

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

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.