试图替换“\”使用 javascript 作为 json 解析器的 char
我有以下 JavaScript 行:
YAHOO.lang.JSON.parse(txt)
其中文本是从数据库中提取的字符串。这是我返回的问题字符串之一的示例:
5000\25\30%
据我所知,JSON 解析器在 / 字符上抛出语法错误。我查看了这里的线程,其中大多数都说将其更改为“//”,但我从数据库中提取了数百个值,因此我无法更改它们的源。我试图让它用空字符串替换“/”字符,因为我实际上不必显示“/”,但我遇到了困难。我当前的替换代码如下所示:
if(substr.indexOf("\\") > 0){
substr.replace(/\\/g , "");
}
但什么也没有发生。有时“indexOf”检查失败,所以我尝试对每个字符串运行替换,但它仍然没有替换任何“\”字符。所以这是我的问题:如果我返回一个包含一个或多个 '\' 字符的字符串,并且需要使用 javascript 为 JSON 解析器删除它们,我该怎么做?或者如何让 JSON 解析器接受 '\' 字符而不更改源字符串。
编辑:我认为问题可能是“\2”和所有其他正在评估和排除不执行任何操作的字符。这些字符总是被转义,因此无法替换。这甚至可以修复错误吗?
I have the following line of javascript:
YAHOO.lang.JSON.parse(txt)
Where text is a string that is pulled from the database. This is an example of one of the problem strings I'm getting back:
5000\25\30%
The JSON parser is throwing syntax errors on the / character as far as I can tell. I looked through threads here and most of them are saying to change it to "//" but I'm pulling hundreds of values from a database so I can't change their source. I'm trying to get it to replace the '/' char with just the empty string since I don't actually have to display the '/', but I'm having difficulties. My current replace code looks like this:
if(substr.indexOf("\\") > 0){
substr.replace(/\\/g , "");
}
but nothing is happening. Sometimes the "indexOf" check fails, so I tried running the replace on every string and it still didn't replace any of the '\' chars. So here is my question: If I get back a string with one or more '\' characters and need to remove them for a JSON parser using javascript, how do I do that; or how do I get a JSON parser to accept the '\' char without changing the source string.
Edit: I think what might be the problem is that "\2" and all the other ones are evaluating and exceping characters that don't do anything. These characters are always escaped so they cannot be replaced. Is this even possible to fix the error?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我能够弄清楚这一点。所要做的就是更改从数据库创建初始返回的 jsonWrite 并执行 ReplaceAll("\x5C", "\"),用 html 代码替换该字符,以便它仍然显示并能够被解析。
I was able to figure this out. What it took was changing the jsonWrite that was creating the inital return from the database and doing a replaceAll("\x5C", "\"), replacing the character with the html code for it so it still displays and is able to be parsed.