在JSON的哈希中查找嵌套哈希

时间:2013-11-13 18:55:39

标签: ruby-on-rails ruby json

我的JSON结构如下:

{
"result": {
    "status": 1,
    "num_results": 100,
    "total_results": 500,
    "results_remaining": 400,
    "matches": [
        {
            "match_id": 381440228,
            "match_seq_num": 347730324,
            "start_time": 1384292236,
            "lobby_type": 0
        },
        {
            "match_id": 380304327,
            "match_seq_num": 346687624,
            "start_time": 1384203633,
            "lobby_type": 0
        }
                    ]

下面会有更多的“匹配”。

我想知道的是我如何通过'match_id'拉出'matches'数组中的一个哈希值。

由于match_id在哈希内部,我如何通过搜索该值来提取整个哈希?

2 个答案:

答案 0 :(得分:0)

一种方法可能是:

hash["result"]["matches"].select {|m| m["match_id"] == match_id }

答案 1 :(得分:0)

怎么样

hash["result"]["matches"].find { |m| m["match_id"] == "your id here" }

请参阅Enumberable#find