ruby 解析 HTTParty 数组 - json
对 Ruby 还很陌生——如果有人问这个问题,我提前道歉。
我正在使用 HTTParty 从 API 获取数据,它返回一个 JSON 数据数组,我不太清楚如何解析该数据。
#<Net::HTTPOK:0x1017fb8c0>
{"ERRORARRAY":[],"DATA":[{"ALERT":1,"LABEL":"hello","WATCHDOG":1},{"LABEL":"goodbye","WATCHDOG":1}
我想第一个问题是我真的不知道我在看什么。当我执行 response.class
时,我得到 HTTParty::Response
。它似乎是数组内的哈希?我不知道。不管怎样,我想要一种方法来获取每个单独数组的“LABEL”,所以结果将是“hello”,“goodbye”。
我将如何去做呢?
Still new to Ruby - I apologize in advance if this has been asked.
I am using HTTParty to get data from an API, and it is returning an array of JSON data that I can't quite figure out how to parse.
#<Net::HTTPOK:0x1017fb8c0>
{"ERRORARRAY":[],"DATA":[{"ALERT":1,"LABEL":"hello","WATCHDOG":1},{"LABEL":"goodbye","WATCHDOG":1}
I guess the first question is that I don't really know what I am looking at. When I do response.class
I get HTTParty::Response
. It appears to be a Hash inside an array? I am not sure. Anyway, I want a way to just grab the "LABEL" for every separate array, so the result would be "hello", "goodbye".
How would I go about doing so?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你不需要逐个解析它。你可以做的是将 ':' 替换为 '=>'并对其进行评价。
示例:假设您有
["one":"a","two":"b"]
,您可以将 s 设置为等于该字符串并执行eval s.gsub(/^ \[/, '{').gsub(/\]$/, '}').gsub('":', '"=>')
将产生一个 ruby 哈希(检查显示{“one”=>“a”,“two”=>“b”})或者,您可以执行类似这样的操作
parsed_and_a_hash 是一个哈希!
you don't need to parse it per say. what you could do is replace ':' with '=>' and evaluate it.
example: say you have
["one":"a","two":"b"]
, you could set s to equal that string and doeval s.gsub(/^\[/, '{').gsub(/\]$/, '}').gsub('":', '"=>')
will yield a ruby hash (with inspect showing {"one"=>"a", "two"=>"b"})alternatively, you could do something like this
parsed_and_a_hash is a hash!
如果这是 JSON,那么最好的选择是安装一个处理 JSON 格式的库。重新发明轮子确实没有意义(尽管它很很有趣)。请查看这篇文章。
如果您知道 JSON 数据将始终采用完全相同的格式,那么您可以在没有 JSON gem 的情况下管理相对简单的东西。但我不确定这是否值得这么麻烦。
If that's JSON, then your best bet is to install a library that handles the JSON format. There's really no point in reinventing the wheel (although it is fun). Have a look at this article.
If you know that the JSON data will always, always be in exactly the same format, then you might manage something relatively simple without a JSON gem. But I'm not sure that it's worth the hassle.
如果您在使用 json gem 时遇到困难,请考虑使用 Crack gem。它还具有解析 xml 的额外好处。
If you're struggling with the json gem, consider using the Crack gem. It has the added benefit of also parsing xml.