How to JSON parse in windows 8
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 lJSON.parse('{lhs: "32 Japanese yen",rhs: "0.30613818 Euros",error: "",icc: true}')SyntaxError: Unexpected token lJSON.parse('{lhs: "32 Japanese yen",rhs: "0.30613818 Euros",error: "",icc: 1}')SyntaxError: Unexpected token lJSON.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.
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...