Rails JSON非标准字符(Rails JSON non

编程入门 行业动态 更新时间:2024-10-22 14:33:59
Rails JSON非标准字符(Rails JSON non-standard characters)

我的数据库中有一个包含此示例子字符串的字符串。

string = "\357\277\275\357\277\275"

当我尝试将其转换为JSON时,我会遇到很多这些坏男孩(因为他们是非ASCII字符)。

然后,当jQuery尝试解析JSON时,它只是疯了,并给了我一个SyntaxError: Unexpected Token

这有三种可能的解决方案。

将字符串转换为JSON可接受的值 删除有问题的字符 用诸如“无效字符”之类的消息替换字符串

我对这些都很好,但不知道如何去做。 思考?

I have a string within my database that contains this sample substring.

string = "\357\277\275\357\277\275"

When I try to convert this to JSON, I get a lot of these bad boys (since they are non-ASCII characters).

Then, when jQuery tries to parse the JSON, it just craps out and gives me a SyntaxError: Unexpected Token

Here are three possible solutions.

Convert the string into JSON acceptable values Remove the offending characters Replace the string with a message such as "Invalid Characters"

I am fine with any of these, but don't know how to go about them. Thoughts?

最满意答案

"\357\277\275"是替换字符( )的ascii八进制表示。 这表明当您转换为JSON时,字符串中存在非ascii字符。 理想情况下,您可能希望识别非ascii字符如何进入您的数据上游,但简单的解决方法是删除它们:

clean_string = "absr\357\277\275/xyz".gsub("\357\277\275","") #=> "absr/xyz"

In order to strip unprintable characters from strings in Ruby, you can use the following regex.

"your_string".gsub!(/[^[:print:]]/, '')

更多推荐

本文发布于:2023-04-29 03:30:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1334546.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:非标准   字符   Rails   JSON

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!