ngplayground
ngplayground

Reputation: 21667

json and javascript getting value

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

Upvotes: 0

Views: 59

Answers (2)

h2ooooooo
h2ooooooo

Reputation: 39550

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

Upvotes: 1

pb2q
pb2q

Reputation: 59647

Use the parseJSON function:

var jsonStr = '{"id":true,"username":"mynameisdonald"}';
var obj = $.parseJSON(jsonStr);
console.log(obj.username);

Upvotes: 2

Related Questions