我的数据库中有一个包含此示例子字符串的字符串。
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:]]/, '')更多推荐
发布评论