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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With