I posted this gist a few years ago as a quick memo for myself. I never expect this little gist to rank up in top 3 search result and getting so many helpful feedbacks. Since it gets viewed quite often, I decided to revise this post so that it may be a little more helpful. Thank you again for the feedback!
require "json"
class MyJSON
def self.valid?(value)
result = JSON.parse(value)
result.is_a?(Hash) || result.is_a?(Array)
rescue JSON::ParserError, TypeError
false
end
end
# true - valid JSON object
MyJSON.valid?(%({"a": "b", "c": 1, "d": true}))
MyJSON.valid?("{}")
MyJSON.valid?("[1, 2, 3]")
# false - may be a valid JSON string, but not a valid JSON object
MyJSON.valid?("")
MyJSON.valid?("123")
# false - not a valid JSON string
MyJSON.valid?(nil)
MyJSON.valid?(true)
MyJSON.valid?(123)
Ref: Is this simple string considered valid JSON?
So that it can be easily reused. But It's totally fine if you want to re-write it into a method, class or just copy part of the snippet.
Because strings are valid JSON string and can be parsed successfully by JSON.parse
.
But ensuring JSON objects is what I am looking for, thus extra checking is needed.
To handle edge cases like parsing JSON.parse(123)
require "json"
def valid_json?(json)
begin
JSON.parse(json)
return true
rescue Exception => e
return false
end
end
I would follow @benoittgt and only rescue from the specific error you are searching for.
And also, simplify by using
!!
operator.