sonicboom sonicboom - 1 year ago 93
JSON Question

check if name == keyword

So i have a json here and im trying to search for name

I am trying to read through the whole json, and only match to name. But im not sure how to go about that.

I parsed the json below into a variable called jsondata

and created this loop here to read it.

jsondata.each do |links|
puts links

But how can i go about only reading the name field and matching it to a string? Lets say im looking looking for the word leo.


Cam Cam
Answer Source

You can search each string under the key of "name" for the needle you're looking for using String#include? or String#index. The Enumerable method select would be a good choice for selecting only the hashes that contain the data you're looking for:

jsondata["files"].select{|h| h["name"].include? "leo" }

This presumes you have parsed the json data into a Ruby hash:

jsondata = {"files"=>[

jsondata["files"].select{|h| h["name"].include? "leo" }
#  => [{"name"=>"leo.jpg", "size"=>51678, "deleteType"=>"DELETE", "deleteUrl"=>"http=>//", "url"=>"http=>//"}, {"name"=>"leo2.jpg", "size"=>41407, "deleteType"=>"DELETE", "deleteUrl"=>"http=>//", "url"=>"http=>//"}]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download