multidimensional-arrayruby-on-rails-5ruby-hash

How do I select a specific property in nested array json rails 5


I need help with this. I would like to access transactionCustomFields and I would like to get the token from the response.

  {
   "event":"TRANSACTION OUTCOME",
  "timestamp":1672749136029,

  "data":{
  "transactionId":"b5247b19-1e14-4f3e-818f-a3b1554dd64b",
  "transactionStatus":"SUCCESS",
  "statusDescription":"SUCCESS",
  "transaction":{
     "id":"b5247b19-1e14-4f3e-818f-a3b1554dd64b",
     "paymentMethod":"MOBILE_MONEY",
     "transactionType":"PULL",
     "phoneNumber":"+256754187853",
     "telecom":"AIRTEL",
     "amount":500,
     "status":"SUCCESS",
     "narration":"",
     "failedDescription":null,
     "webhookUrl":"https://webhook.site/cbf423c2-15f5-46f3-9c76-1dcc0b9a2e18",
     "createdAt":"2023-01-03T12:32:04.176Z",
     "transactionCustomFields":[
        {
           "id":"1fc25a5c-ba0b-4959-b295-31628d8da0e1",
           "key":"token",
           "value":"31644"
        },
        {
           "id":"2686effb-4f40-45ac-867f-b39d84282dae",
           "key":"reference",
           "value":"1672749122"
        }
     ]
  }}}

This is the JSON response


Solution

  • Assuming you want to access the first item of the "transactionCustomFields" array and its id/key you could do something like this.

    json_object = JSON.parse(response)
    
    json_object['data']['transaction']["transactionCustomFields"][0]["key"] //gives you token
    json_object['data']['transaction']["transactionCustomFields"][0]["id"] //gives you "1fc25a5c-ba0b-4959-b295-31628d8da0e1"
    

    Hope this answers your question