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.
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);
express.js cannot parse JSON objects on its own. Try using the body-parser
var app = require('express')();
var bodyParser = require('body-parser');
var multer = require('multer'); // v1.0.5
var upload = multer(); // for parsing multipart/form-data
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.post('/profile', upload.array(), function (req, res, next) {
console.log(req.body);
res.json(req.body);
});
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/