简体   繁体   English

JSON.parse()和$ .parseJSON()中的“未捕获的SyntaxError:意外的令牌?”

[英]“Uncaught SyntaxError: Unexpected token ?” in both JSON.parse() and $.parseJSON()

I have no idea why I am getting this and I have spent over a day trying to mess with the code. 我不知道为什么要得到这个,我花了整整一天的时间试图弄乱代码。 Now the simplest I can get is this (Trying to build a javascript array with an escaped string coming from a database): 现在,我能得到的最简单的方法是(尝试使用来自数据库的转义字符串构建JavaScript数组):

vat test = '["<script>var bob = \\"This is ok\\"</script>", "<script>search.replace(/!|\\\?)/g, \\"\\")</script>"]';

So far, so good. 到现在为止还挺好。

Then this breaks and returns the error: 然后这会中断并返回错误:

JSON.parse(test);

To give an idea, the original 2 array items were this: 给出一个想法,原始的2个数组项是:

<script>var bob = "This is ok"</script>
<script>search.replace(/!|\?)/g, "")</script>

All the codes of any kind that were entered in the database have always worked, except now, because of that question mark from a user-entered line in my CMS. 除了现在,由于我CMS中用户输入的行中的问号,所有输入数据库的所有代码都一直有效。 If I remove it or replace the question mark by anything else, it works. 如果我删除它或将问号替换为其他任何东西,它将起作用。

I cannot change the regex so to make it work any other way, I am not the one who entered this. 我不能更改正则表达式,以便使其以任何其他方式起作用,我不是输入此正则表达式的人。 Plus this is a simplified version of a whole script, I just narrowed it to the question mark. 加上这是整个脚本的简化版本,我只是将其缩小为问号。

I also looked online if the question mark had a special meaning for json, did not find anything. 如果问号对json有特殊含义,我什么也没找到。

I wish I could have sent a fiddle instead of just code, but jsfiddle doesn't let me add the tag in the javascript window. 我希望我可以发送一个小提琴而不只是代码,但是jsfiddle不允许我在javascript窗口中添加标签。

JSON.parse('["<script>var bob = \\"This is ok\\"</script>", "<script>search.replace(/!|\\\?)/g, \\"\\")</script>"]')
SyntaxError: Unexpected token ?

There are two unescapes going on here, so you need an extra \\ before the ? 这里有两种unescape,所以在?之前需要额外的\\ ?

JSON.parse('["<script>var bob = \\"This is ok\\"</script>", "<script>search.replace(/!|\\\\?)/g, \\"\\")</script>"]')
["<script>var bob = "This is ok"</script>", "<script>search.replace(/!|\?)/g, "")</script>"]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM