Search code examples
ruby-on-railsruby

How to get keys from hash in Rails


In page.body I am getting this:

page.body = "{\"error\":\"Sorry, that is an invalid URL\"}

I want to fetch only "Sorry, that is an invalid URL". When I am fetching like this page.body[:error], I am getting no implicit conversions. When I am trying to see error is there or not like this:

  page.body.include? "error" 
  true

Can anyone help me to get error values.


Solution

  • You need to parse the json, to make a hash out of it and then you can check if the key exist like this:

    require 'json'
    JSON.parse(page.body).key? "error"
    #=> true
    

    To fetch the error value, it's almost the same approach:

    JSON.parse("{\"error\":\"Sorry, that is an invalid URL\"}")["error"]
    # => "Sorry, that is an invalid URL" 
    # or
    JSON.parse("{\"error\":\"Sorry, that is an invalid URL\"}").fetch("error")
    # => "Sorry, that is an invalid URL"