尝试将哈希转换为json字符串时出现错误JSON::GeneratorError: source sequence is illegal/malformed utf-8。我想知道这是否与编码有关,我如何才能使json只处理xae?

$ irb
2.0.0-p247 :001 > require 'json'
=> true
2.0.0-p247 :002 > a = {"description"=> "iPhone\xAE"}
=> {"description"=>"iPhone\xAE"}
2.0.0-p247 :003 > a.to_json
JSON::GeneratorError: source sequence is illegal/malformed utf-8
  from (irb):3:in `to_json'
  from (irb):3
  from /Users/cchen21/.rvm/rubies/ruby-2.0.0-p247/bin/irb:16:in `<main>'

最佳答案

\xAE不是utf-8中的有效字符,必须改用\u00AE

"iPhone\u00AE"
#=> "iPhone®"

或相应转换:
"iPhone\xAE".force_encoding("ISO-8859-1").encode("UTF-8")
#=> "iPhone®"

关于ruby - Ruby to_json问题,错误为“非法/格式错误的utf-8”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18067203/

10-12 01:25
查看更多