Last active
April 23, 2023 07:43
-
-
Save dkam/1b2a04e647c0076d800582b1aae08c1b to your computer and use it in GitHub Desktop.
Check JSON is valid
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def valid_json?(string) | |
result = JSON.parse(string) | |
result.is_a?(Hash) || result.is_a?(Array) | |
rescue JSON::ParserError, TypeError | |
false | |
end | |
def valid_json(string, default: []) | |
result = JSON.parse(string) | |
return result if result.is_a?(Hash) || result.is_a?(Array) | |
default | |
rescue JSON::ParserError, TypeError | |
default | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment