简体   繁体   中英

Rails JSON non-standard characters

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.

  1. Convert the string into JSON acceptable values
  2. Remove the offending characters
  3. 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" is the ascii octal representation of the Replacement Character( ). This indicates that when you converted to JSON there were non-ascii characters in your string. Ideally, you would want to identity how non-ascii characters are getting into your data upstream but the easy fix is to just delete them:

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

为了从Ruby中的字符串中去除不可打印的字符,可以使用以下正则表达式。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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