如何从Ruby中的JSON中的特定键获取每个值

时间:2019-12-26 15:42:24

标签: json ruby key-value

我有以下JSON:

{"connection": {
"informations": {},
"id_user": 6909,
"subscriptions": [
    {
        "id_source": 69825,
        "documents": [
            {
                "id_subscription": 5265,
                "thumb_url": "https://test-sandbox.biapi.pro/2.0/users/me/documents/1244/thumbnail/test%40hotmail.fr_305146953_thumbnail.png",
                "name": "Facture de 44.96€ du 2019-11-18",
                "id_thumbnail": 40343,
                "url": "https://test-sandbox.biapi.pro/2.0/users/me/documents/1244/file/test%40hotmail.fr_305146953.pdf",
                "untaxed_amount": null
            },
            {
                "id_subscription": 5265,
                "thumb_url": "https://mooncard23-sandbox.biapi.pro/2.0/users/me/documents/1245/thumbnail/test%40hotmail.fr_290804394_thumbnail.png",
                "name": "Facture de 13.98€ du 2019-05-29",
                "url": "https://mooncard23-sandbox.biapi.pro/2.0/users/me/documents/1245/file/test%40hotmail.fr_290804394.pdf",
                "untaxed_amount": null
            }
        ]
    }
]
}
}

我尝试获取“ https://test-sandbox.biapi.pro/2.0/users/me/documents/1246/file/test%40hotmail.fr_274475652.pdf”之类的所有值

我的JSON在我的控制器中呈现为:

render json: params.to_json

当我尝试以这种方式获取所有值URL时:

params.dig('connection','subscriptions').each_with_object([]) { |x, arr| x['documents'].each { |d| arr << d['url'] } } 

我遇到错误undefined method each_with_object for nil:NilClass

1 个答案:

答案 0 :(得分:0)

这是简单易懂的解决方案,易于理解。 您可以尝试以下方法:

[[
 "https://mooncard23-sandbox.biapi.pro/2.0/users/me/documents/1244/file/test%40hotmail.fr_305146953.pdf",
 "https://mooncard23-sandbox.biapi.pro/2.0/users/me/documents/1245/file/test%40hotmail.fr_290804394.pdf",
 "https://mooncard23-sandbox.biapi.pro/2.0/users/me/documents/1246/file/test%40hotmail.fr_274475652.pdf"
]]
{{1}}