在 Ruby 1.8.7 中将带有二进制数据的 YAML 响应转换为 UTF-8 [英] Converting a YAML response w/ binary data to UTF-8 in Ruby 1.8.7
问题描述
我正在从 API 中提取响应并接收:
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
body_tgt 值应该是几个日文字符(回答),但为了安全运输,它们正在被转换.我在 1.8.7,所以我不能 force_encoding.有没有办法解包()它们?
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?
推荐答案
这似乎是一个 YAML 文档,而不是 JSON,使用 YAML 的二进制数据语言(反过来使用 base64 编码).
That appears to be a YAML document, not JSON, using YAML's binary data language (which in turn uses base64 encoding).
Ruby 内置的 YAML 解析库应该能够为您解析数据:
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"}}}
为了生成直接嵌入 UTF-8 的 YAML,而不是转义为二进制对象,您可以使用 ya2yaml,又一个 to_yaml"实现,它可以产生编码为 UTF-8 的输出.安装 ya2yaml
gem,然后调用它:
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)
这篇关于在 Ruby 1.8.7 中将带有二进制数据的 YAML 响应转换为 UTF-8的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!