Convert String to Json to apply JSON Patch

Viewed 1670

I am trying to take a request using postmon in for a json string to apply json patch. The issue is I am unable to convert the string to json one the data is posted via variable. Every time I do

JSON.parse(document);

I am getting the following error:

SyntaxError: Unexpected token ' in JSON at position 1

The Data which I am sending is the following

{"document":"{'baz': 'qux', 'foo': 'bar'}"}

via postman using a post method.

I am using req.body to get hand on post data

2 Answers

Well document is already an object which points to the document global variable in window, and it's not a string so you can't parse it. That's why you will get :

SyntaxError: Unexpected token ' in JSON at position 1

So if you has an object you need to stringify it before you can parse it, so use:

JSON.stringify(doc);

Note:

Note that if you have declared document as a variable, document is a bad name for a variable as it's already a global object name in the window which points to the current document, and using it will lead to many errors.

But if it's inside your data, it would be JSON.parse(data) as you are dealing with data object from your response.

Demo:

var data = {"document":"{'baz': 'qux', 'foo': 'bar'}"};
console.log(JSON.stringify(data));

"{'baz': 'qux', 'foo': 'bar'}" is not a valid json string.

Single quotes are not correctly formatted json so the parser will not accept single quote and will throw below error

SyntaxError: Unexpected token ' in JSON at position 1

enter image description here

So to be able to parse that string as json you will need to replace ' quotes with " quotes using str.replace() before parsing

Demo:

var data = {"document":"{'baz': 'qux', 'foo': 'bar'}"};
console.log(JSON.parse(data.document.replace(/'/g, '"')))  

Related