Edwin De Los Santos
Edwin De Los Santos

Reputation: 18

How to parse String Object with '\n' and \\\

I'm trying to read AWS SNS JSON, but when I try to parse the string object in jsonlog I get a

SyntaxError:Unexpected token \ in JSON at position 1

I tried to replace '\n' and '\\' but the string is not showing changes

var log = snslogs[i].jsonlog;
logs.push(JSON.parse(`${log}`));

I expect the JSON.parse to create an object.

Upvotes: 0

Views: 1163

Answers (1)

DDupont
DDupont

Reputation: 451

My JSON.parse accepts the \n at the beginning of the string, not sure if that "position 1" in the error is misleading.

The problem I see is the trailing comma after the last field - that is not allowed in JSON. So your inputs are not valid JSON, but if you really want to accommodate them anyway, try this:

JSON.parse(log.replace(',}$','}'))

or if the initial \n is a problem still, then this:

JSON.parse(log.replace(/\\n/,'').replace(',}$','}'))

You may need to play with the regex if you get other forms of the trailing comma (like with a space after it, etc).

Upvotes: 1

Related Questions