define String#json? to return boolean value if the object is json string

I was looking for a method that return boolean value if the object is json string.

I think there is no support for this idea on activesupport/lib/active_support/core_ext/string .

Here is my proposal to include this feature.

activesupport/lib/active_support/core_ext/string/json.rb

class String

An object is json string if it’s parseable by JSON.parse.

return true if it’s parseable.

return false if it is not parseable.

def json?

!!JSON.parse(self)

rescue

false

end

end

Note that I’m not on the core team, so my answer is far from final, but: just a heads up that the current refrain on changes to Active Support (and particularly the core extensions) is roughly “We avoid adding new things to Active Support unless they are used in the framework or by a large number of applications, so we need to know why you think this feature is useful to take any decision” — example.

You could open a PR with your change to get more discussion since it’s a reasonably minimal and understandable diff, but expect pushback unless you have a particularly compelling use case. Since this is a core extension update to String, you could also lobby to have it included in Ruby directly instead.

Definitely don't see this in the String class.

If you like that API you can throw that code in the initializers of your
app, though.