Curious_Bop Curious_Bop - 1 year ago 106
Ruby Question

Ruby iterate through JSON response and return values

I am trying to iterate through JSON and I keep falling foul of the following error:

no implicit conversion of String into Integer (TypeError)

What I want to do is iterate through my response and based my rules return a segment of data. My response is as follows:

data = JSON.parse(response)

data = (whats below)

“summary”: {
“Id”: 5452,
“IdOutcome”: "Scored",
“Results”: [
“test”: "car",
“value”: 10.0,
“num”: 0
“test”: "carz",
“value”: 0.0,
“num”: 0
“test”: "bars",
“value”: 10.0,
“num”: 1

So in the example response above I want to iterate through "Results" and return back either "test" or heck even all of the block for the highest num value. So in the example below I would be returned


or just


SO essentially I just need to iterate through the returned array data.

Answer Source

You want to use Enumerable#max_by:

max_result = data["summary"]["Results"].max_by {|r| r["num"] }
# => { "test" => "bars",
#      "value" => 10.0,
#      "num" => 1
#    }

# => "bars"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download