1

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.

0

6 Answers 6

4

you parsing Object to Object?

JSON.parse() expects string:

var str = '{"test": "info"}';
obj = JSON.parse(str);
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

1

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);

2 Comments

var str = '{ test: 'info'}'; obj = JSON.parse(str); I write, but the same mistake.
Mind your quote types, and/or make sure you escape embedded quotes.
1

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);
});

Comments

0

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/

Comments

0

The thing you are calling str is actually already an object. JSON is not necessary, pure JavaScript is all you need:

var obj = { test: 'info'};

console.log( JSON.stringify(obj) );  // JSON output

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.