最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Escaping double-quote in JSON Object - Stack Overflow

programmeradmin1浏览0评论

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
Add a ment  | 

1 Answer 1

Reset to default 4

str.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.

发布评论

评论列表(0)

  1. 暂无评论