Reputation: 933
So, I'm using node.js and trying to create a simple express REST API, using node-mysql, express (of course), and other things.
I've pretty much had no issues untill now, whenever I execute a db query, it returns an result as such:
[ { id: 18,
username: 'test',
passwordHash: 'redacted',
admin: 0,
created: Fri Jun 13 2014 17:17:10 GMT-0700 (Pacific Daylight Time) } ]
JSON.parse, when used on this, returns a SyntaxError: Unexpected Token o
.
I've looked into JSON validators, which states this is invalid JSON. Am I missing something here, it appears to be JSON. I'm slightly new to JavaScript, so apologies if this is easy.
Upvotes: 1
Views: 957
Reputation: 385144
It is not JSON.
It is almost valid JavaScript object literal notation (after which JSON is named), but even there it's missing a few things, such as quotation marks around the created
string.
In fact it seems that you have a JavaScript object already; passing that to JSON.parse
will coerce it into a string, which is [object <some type>]
, the first invalid/unexpected character of which is 'o'
… which is what your error message says.
It seems like you've gotten confused between the literal notation in a JavaScript script, which results in an object, and the text format known as JSON, and decided that you must always "parse" objects in order to use them.
Upvotes: 1
Reputation: 2972
So when you try to parse an object you will get an error. JSON.parse takes a string and parses it into an object. You already have an object, you don't need to parse it.
var obj = {};
JSON.parse(obj)
SyntaxError: Unexpected token o
JSON is not a JavaScript Object.
now if you stringify your obj, you'll get JSON back:
var obj = [ { id: 18, username: 'test', passwordHash: 'redacted', admin: 0, created: 'Fri Jun 13 2014 17:17:10 GMT-0700 (Pacific Daylight Time)' } ];
JSON.stringify(obj);
"[{"id":18,"username":"test","passwordHash":"redacted","admin":0,"created":"Fri Jun 13 2014 17:17:10 GMT-0700 (Pacific Daylight Time)"}]"
Upvotes: 3
Reputation: 211580
If you're getting a JavaScript object back, and it appears you are, just use it. There's no need to parse it.
Upvotes: 1