Skip to content Skip to sidebar Skip to footer

Not Returning Valid Json?

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

Solution 1:

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)"}]"

Solution 2:

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.

Solution 3:

If you're getting a JavaScript object back, and it appears you are, just use it. There's no need to parse it.

Post a Comment for "Not Returning Valid Json?"