I'm trying to parse a json object using JSON.parse of an object similar to this one:
{"id":3,"status_id":3,"project_class":"B","project_name":"Magic i-S6/" i-F1"}
Where the problem stands out to be "Magic i-S6/" as the value for project_name
And it's returning an error like this one
Uncaught SyntaxError: Unexpected token i in JSON at position 102
I've tried using
str.replace(/"/g, '\\"');
But it doesn't work.
What should I do to prevent this error?
I'm trying to parse a json object using JSON.parse of an object similar to this one:
{"id":3,"status_id":3,"project_class":"B","project_name":"Magic i-S6/" i-F1"}
Where the problem stands out to be "Magic i-S6/" as the value for project_name
And it's returning an error like this one
Uncaught SyntaxError: Unexpected token i in JSON at position 102
I've tried using
str.replace(/"/g, '\\"');
But it doesn't work.
What should I do to prevent this error?
Share Improve this question edited Mar 22, 2018 at 12:00 James asked Mar 22, 2018 at 11:50 JamesJames 4,0723 gold badges28 silver badges39 bronze badges 4-
Apply
str.replace(/"/g, '\\"');
at the time the JSON is constructed, on each parameter value. – Adder Commented Mar 22, 2018 at 11:54 - 1 @Adder — Ick. Don't do that. Get a proper JSON serialisation library instead. – Quentin Commented Mar 22, 2018 at 11:56
-
It depends how you're getting the value. Whatever is converting the object to JSON should be doing in a standard manner in which case
JSON.parse()
should be able to correctly recreate the object. The problem is most likely in the serialization so you should fix that. – Reinstate Monica Cellio Commented Mar 22, 2018 at 11:57 - 1 This is proof of the general rule: don't handcraft serialised data. – lonesomeday Commented Mar 22, 2018 at 11:58
1 Answer
Reset to default 4str.replace(/"/g, '\\"');
would replace all the quotes in the JSON with escaped ones: Even the quotes that are needed to delimit the strings in the JSON.
You should fix this by changing the code which generates the broken JSON.
Trying to fix it after receiving it is never going to be reliable.
You could attempt to target the specific bit of bad data in that particular string of JSON…
str = str.replace('i-S6/"', 'i-S6\\"');
… but that isn't a robust or general solution.
Fixing the bad code which is generating the bad data is the better approach.