sonicboom sonicboom - 5 months ago 20
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
end


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.

{"files":
[{"name":"github.jpeg","size":10852,"deleteType":"DELETE","deleteUrl":"http://gifs.meow.me/github.jpeg","url":"http://gifs.meow.me/github.jpeg"},{"name":"leo.jpg","size":51678,"deleteType":"DELETE","deleteUrl":"http://gifs.meow.me/leo.jpg","url":"http://gifs.meow.me/leo.jpg"},{"name":"leo2.jpg","size":41407,"deleteType":"DELETE","deleteUrl":"http://gifs.meow.me/leo2.jpg","url":"http://gifs.meow.me/leo2.jpg"}]}

Cam Cam
Answer

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"=>[
  {"name"=>"github.jpeg",
   "size"=>10852,
   "deleteType"=>"DELETE",
   "deleteUrl"=>"http=>//gifs.meow.me/github.jpeg",
   "url"=>"http=>//gifs.meow.me/github.jpeg"},
  {"name"=>"leo.jpg",
   "size"=>51678,
   "deleteType"=>"DELETE",
   "deleteUrl"=>"http=>//gifs.meow.me/leo.jpg",
   "url"=>"http=>//gifs.meow.me/leo.jpg"},
  {"name"=>"leo2.jpg",
   "size"=>41407,
   "deleteType"=>"DELETE",
   "deleteUrl"=>"http=>//gifs.meow.me/leo2.jpg",
   "url"=>"http=>//gifs.meow.me/leo2.jpg"}
]}

jsondata["files"].select{|h| h["name"].include? "leo" }
#  => [{"name"=>"leo.jpg", "size"=>51678, "deleteType"=>"DELETE", "deleteUrl"=>"http=>//gifs.meow.me/leo.jpg", "url"=>"http=>//gifs.meow.me/leo.jpg"}, {"name"=>"leo2.jpg", "size"=>41407, "deleteType"=>"DELETE", "deleteUrl"=>"http=>//gifs.meow.me/leo2.jpg", "url"=>"http=>//gifs.meow.me/leo2.jpg"}]