Search code examples
jsonrubyautomated-testscucumberrest-client

Validating JSON response using rest client


I am trying to use rest client in ruby to parse json but I am stuck how to validate the response (extract values from the response). Also I am trying to validate the valid response code(200) response.code does not work. Following is the JSON response and Code that uses rest client to get it:

def self.call_legacy_transactions

  get_response=RestClient::Request.execute(method: :get, url: 'URL', timeout: 15)
  puts(get_response.body)
  json_response = JSON.parse(get_response)
//Dont know how to get the values from response hash. Please suggest

  end

JSON Response:

    [
  {
    "value": "12345678912345",
    "events": [
      {
        "transaction_id": 205,
        "package_name": "",
        "event_codes": [
          465,
          469,
          471,
          474,
          410,
          490,
          1040
        ]
      },
      {
        "transaction_id": 204,
        "package_name": "",
        "event_codes": [
          465,
          469,
          474,
          490
        ]
      },
      {
        "transaction_id": 207,
        "package_name": "",
        "event_codes": [
          465,
          469,
          471,
          474,
          490
        ]
      }
    ]
  }
]

I want the event code for each transaction for each value.


Solution

  • If you just want a flat list of event code integers, you can use:

    json_response.flat_map do |value_data|
      value_data[:events].flat_map do |event_data|
        event_data[:event_codes]
      end
    end
    

    UPDATE based on the comment "I want to extract event codes only where transaction id is 205":

    If there could only ever be one item with that transaction ID:

    json_response.flat_map do |value_data|
      value_data[:events].find do |event_data|
        event_data[:transaction_id] == 205
      end[:event_codes]
    end
    

    If there could be many items with that transaction ID:

    json_response.flat_map do |value_data|
      value_data[:events].select do |event_data|
        event_data[:transaction_id] == 205
      end.flat_map do |event_data|
        event_data[:event_codes]
      end
    end