Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 813
Kalzem Avatar asked Jan 14 '23 23:01

Kalzem


2 Answers

The string you are seeing isn't actually valid JSON as it's property names are not quoted. That is why JSON.parse is throwing an error.

like image 85
Sean Kinsey Avatar answered Jan 21 '23 17:01

Sean Kinsey


Just tried it on Chrome Dev Tools:

JSON.parse("{lhs: \"32 Japanese yen\",rhs: \"0.30613818 Euros\",error: \"\",icc: true}")
SyntaxError: Unexpected token l
JSON.parse('{lhs: "32 Japanese yen",rhs: "0.30613818 Euros",error: "",icc: true}')
SyntaxError: Unexpected token l
JSON.parse('{lhs: "32 Japanese yen",rhs: "0.30613818 Euros",error: "",icc: 1}')
SyntaxError: Unexpected token l
JSON.parse('{"lhs": "32 Japanese yen","rhs": "0.30613818 Euros","error": "","icc": true}')
Object
    error: ""
    icc: true
    lhs: "32 Japanese yen"
    rhs: "0.30613818 Euros"
    __proto__: Object

So it seems a "valid" JSON string should use double quote " to enclose every possible place.

Actually this also happens on PHP's json_decode.

I don't know about Win8JS development, so I'm not sure if you can use response.responeJSON or something like that, but directly parsing response.responseText seems likely to fail.

If you really need to use the responseText, consider @Cerbrus' dangerous eval method.

like image 30
Passerby Avatar answered Jan 21 '23 16:01

Passerby