I installed node.js and express.js and I'm trying to use:
var str = { test: 'info'};
obj = JSON.parse(str);
but it causes an error: SyntaxError: Unexpected token 0 at Object.parse (native)
How can I fix this? Thanks.
you parsing Object
to Object
?
JSON.parse()
expects string
:
var str = '{"test": "info"}';
obj = JSON.parse(str);
Basically JSON.parse() expects string but you were passing object, so instead do this:
var original = { test: 'info'};
var str = JSON.stringify(original);
var restored = JSON.parse(str);
Here's helpful docs about JSON https://developer.mozilla.org/en/Using_native_JSON
str is not a string, but an object. Put the whole thing into a string first, i.e.:
var str = '{ "test": "info"}';
obj = JSON.parse(str);
If you want to create JSON you need to use JSON.stringify
.
var thing = { test: 'info' };
var json = JSON.stringify(thing);
If you want to parse JSON to an object you need to use parse
. Parse expects you to use valid JSON.
var json = '{ "test": "info" }'; //Use double quotes for JSON
var thing = JSON.parse(json);
An easy way to test if you are using valid json is to use something like: http://jsonlint.com/