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

白昼怎懂夜的黑 提交于 2020-01-14 14:43:52

问题


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?


回答1:


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)


来源:https://stackoverflow.com/questions/5277645/converting-a-yaml-response-w-binary-data-to-utf-8-in-ruby-1-8-7

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!