Ruby to_json问题,错误为“非法/格式错误的utf-8"; [英] Ruby to_json issue with error "illegal/malformed utf-8"

查看:119
本文介绍了Ruby to_json问题,错误为“非法/格式错误的utf-8";的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I got an error JSON::GeneratorError: source sequence is illegal/malformed utf-8 when trying to convert a hash into json string. I am wondering if this has anything to do with encoding, and how can I make to_json just treat \xAE as it is?

$ 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代替:

\xAE is not a valid character in UTF-8, you have to use \u00AE instead:

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

或相应地进行转换:

"iPhone\xAE".force_encoding("ISO-8859-1").encode("UTF-8")
#=> "iPhone®"

这篇关于Ruby to_json问题,错误为“非法/格式错误的utf-8";的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆