0

How would I be able to get the username in jquery from the following

{"id":true,"username":"mynameisdonald"}

I have tried console.log(data); which shows the above and when i use console.log(data.username) it shows as undefined

1
  • 2
    is this a string or an actual JSON Object? are you assigning it to variable data at all? Commented Aug 30, 2012 at 12:39

2 Answers 2

2

Use the parseJSON function:

var jsonStr = '{"id":true,"username":"mynameisdonald"}';
var obj = $.parseJSON(jsonStr);
console.log(obj.username);
Sign up to request clarification or add additional context in comments.

Comments

1

In your jQuery call, specify that this is JSON:

$.post(
    "backend.php", 
    data: "nodata",
    function(data) {
        console.log(data.username);
    },
    "json"
);

or use jQuery's parseJSON like so:

$.post(
    "backend.php", 
    data: "nodata",
    function(rawData) {
        var data = $.parseJSON(rawData);
        console.log(data.username);
    }
);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.