开发者

Converting a YAML response w/ binary data to UTF-8 in Ruby 1.8.7

I'm pulling a response from an API and receiving:

      response: 
        job: 
          unit_count: "1"
          slug: Answers
          lc_tgt: ja
          body_tgt: !binary |
            5Zue562U

          lc_src: en
          body_src: Answers
          job_id: "1948888"
      opstat: ok

That body_tgt value should be a开发者_运维知识库 couple Japanese characters(回答), but they are being converted for safe shipping. I'm in 1.8.7, so I can't force_encoding. Is there a way to unpack() them?


That appears to be a YAML document, not JSON, using YAML's binary data language (which in turn uses base64 encoding).

Ruby's built in YAML parsing library should be able to parse the data for you:

> x = YAML.load('      response: 
        job: 
          unit_count: "1"
          slug: Answers
          lc_tgt: ja
          body_tgt: !binary |
            5Zue562U

          lc_src: en
          body_src: Answers
          job_id: "1948888"
      opstat: ok')
 => {"opstat"=>"ok", "response"=>{"job"=>{"slug"=>"Answers", 
"unit_count"=>"1", "lc_tgt"=>"ja", "lc_src"=>"en", "body_tgt"=>"回答",
"job_id"=>"1948888", "body_src"=>"Answers"}}}

In order to produce YAML with UTF-8 directly embedded, instead of escaped as binary objects, you can use ya2yaml, "yet another to_yaml" implementation, which can produce output encoded as UTF-8. Install the ya2yaml gem, and then invoke it as:

> require 'ya2yaml'
> x.ya2yaml(:syck_compatible => true)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜