Search code examples
javascriptwindowsjsonwindows-8winjs

How to JSON parse in windows 8


I am doing a winJS.xhr like this :

var jsonResult;
WinJS.xhr(
{
    url: urlGoogle,
    responseType: 'json'
}
).done(function complete(response) {
    jsonResult = response.responseText;

    console.log(jsonResult);
}, 
//Error and Progress functions
);

The console log shows me this :

{lhs: "32 Japanese yen",rhs: "0.30613818 Euros",error: "",icc: true}

And I want to get the rhs info. So I tried doing

console.log(jsonResult.rhs); 

and

console.log(jsonResult['rhs']);

It only shows me "undefined". Then I realized that when I did a jsonResult[0], it shows me the first character (which is { ) and so on with the index bracket.

I tried to do a JSON.parse(jsonResult); but it creates an error

json parse unexpected character

Solution

  • var test = {lhs: "32 Japanese yen",rhs: "0.30613818 Euros",error: "",icc: true}
    //test.lhs returns "32 Japanese yen"
    

    I am not quite sure why this isn't working for you. Try logging the console.log(typeof jsonResult) to see if the jsonResult is a string or a object. (if it were a string, I'd say JSON.parse should've worked)
    Then log jsonResult itself, and see if you can walk through it's properties. (The google chrome console works like a charm for this)

    In case it is a string, this is a (Somewhat hacky, unsafe) way to do it:

    var result = eval('({lhs: "32 Japanese yen",rhs: "0.30613818 Euros",error: "",icc: true})')
    var result = eval('(' + jsonResult + ')')
    

    (Thanks to @ThiefMaster♦ for some more proper(-ish) use of eval instead of my own abuse of it.)
    You should then be able to access result
    Generally, you don't want to use eval, but if all else fails...