lbennet
lbennet

Reputation: 1103

How to read a javascript object

I am using from Microsoft the Live Connect Developer Center

It returns this type of variable for a contact but I don't know of a simple way to read it, would perform split on it but do not know how to read this object:

{"id":"contact.0d3d6bf0000000000000000000000000", "first_name":"William", "last_name":"Shakespeare", "name":"William Shakespeare", "gender":null, "is_friend":false, "is_favorite":false, "user_id":"2ae098749083cb3d", "email_hashes":["a790b818acfdef744a23bef534dfd9a4a53aa834250bdfe55f6874543129daa6"], "updated_time":"2012-10-04T19:23:34+0000"}

I'd need to access name and email_hashes with what's inside of it: a790b818acfdef744a23bef534dfd9a4a53aa834250bdfe55f6874543129daa6 - without the brackets.

Just don't know how to read this kind of object.

Upvotes: 1

Views: 301

Answers (5)

Joseph at SwiftOtter
Joseph at SwiftOtter

Reputation: 4321

When you get your variable with the JSON, do this:

var stringData = {}, // Incoming data
    data = JSON.parse(stringData);

Then, you can access the variables like this:

var id = data.id,
    firstName = data.first_name;

To access array values, do this:

var emailHashes = data.email_hashes;
if (emailHashes.length > 0) {
    var i = 0;

    for (; i < emailHashes.length; i++) {
         // perform some action on them.
    }         
}

Upvotes: 0

Akhil F
Akhil F

Reputation: 7740

if

var x = {"id":"contact.0d3d6bf0000000000000000000000000", "first_name":"William", "last_name":"Shakespeare", "name":"William Shakespeare", "gender":null, "is_friend":false, "is_favorite":false, "user_id":"2ae098749083cb3d", "email_hashes":["a790b818acfdef744a23bef534dfd9a4a53aa834250bdfe55f6874543129daa6"], "updated_time":"2012-10-04T19:23:34+0000"}

then

x.email_hashes

returns

["a790b818acfdef744a23bef534dfd9a4a53aa834250bdfe55f6874543129daa6"]

and

x.email_hashes[0]

returns

"a790b818acfdef744a23bef534dfd9a4a53aa834250bdfe55f6874543129daa6"

Upvotes: 0

Brett
Brett

Reputation: 2785

The response you're receiving is a key/value pair. You can access any value with the key

obj[key] // value

or

obj.key // value

Upvotes: 0

Vlad Magdalin
Vlad Magdalin

Reputation: 1690

That looks like JSON. If you're using jQuery, you could do something like this:

var jsonData = $.parseJSON('{"id":"contact..."}');
alert('name: ' + jsonData.id);

See the docs for more usage examples: http://api.jquery.com/jQuery.parseJSON/

Upvotes: 0

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324620

JSON.parse() is specifically designed to take a string in JSON format and produce a JavaScript object, from which you can then access properties.

Upvotes: 3

Related Questions