试图替换“\”使用 javascript 作为 json 解析器的 char

发布于 2024-09-25 20:47:47 字数 635 浏览 3 评论 0原文

我有以下 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

许仙没带伞 2024-10-02 20:47:47

我能够弄清楚这一点。所要做的就是更改从数据库创建初始返回的 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文