0

I'm using the code below to construct a JSON object that looks like this:

{"contacts":[{"provider":"Yahoo","firstName":"myname","lastName":"surname","nickname":"mynick","email":"myemail@hotmail.com","photoURL":"http://l.yimg.com/dh/ap/social/profile/profile_bxx.png"}]};

var data = {};
var contacts;
var gc = $.when(gigya.socialize.getContacts({callback: function(response){
  data['contacts'] = response.contacts.asArray();
}}));
gc.done(function(response) {
  contacts = data;
});
console.log(contacts);

When I pass the resulting contacts object to Google soy template, the JSON object doesn't seem well constructed.

With the code above, how do I construct a valid JSON object?

Thanks for helping out.

drecute
  • 748
  • 4
  • 11
  • 29
  • 4
    `getContacts()` is probably asynchronous, which would mean it's trying to log `contacts` before `contacts = data` is evaluated. Try moving `console.log(contacts)` into the `.done()` callback. For more info with a similar sample, see http://stackoverflow.com/q/14220321. – Jonathan Lonowski Sep 17 '13 at 02:44
  • I can get the value of `contacts` outside of `.done()`. The problem is with getting a valid JSON output – drecute Sep 17 '13 at 02:47
  • `var asJSON =`[`JSON.stringify(contacts)`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) – Jonathan Lonowski Sep 17 '13 at 02:50
  • You don't need `$.when` here. Just use `gc = gigya.socialize.getContacts(...); gc.done(...);`. – user229044 Sep 17 '13 at 02:59
  • @drecute: Why are you using the promise pattern then? – Bergi Sep 17 '13 at 04:14
  • @Bergi Because I need access to `contacts` outside of the async callback. – drecute Sep 17 '13 at 08:31
  • @drecute: That's impossible. Promises are still asynchronous. Everything that depends on them must be another promise. – Bergi Sep 17 '13 at 14:55

1 Answers1

0

The object seems ok,

try using JOSN.stringify() example jsFiddle
or JSON.parse()

You can see in example, you can turn object into valid JSON and reverse into valid JS object.


Regarding your code

  1. What do you get from response ?
  2. And why do you use response here if you do not make use of it?

    gc.done(function(response) {
      contacts = data;
    });
    

I would change this line EDITED

data['contacts'] = response.contacts.asArray();

to

contacts = JSON.parse(response.contacts);

and remove

gc.done(function(response) {
  contacts = data;
});
skmasq
  • 4,470
  • 6
  • 42
  • 77