Checking if a string is valid json before trying to parse it?

RubyJson

Ruby Problem Overview


In Ruby, is there a way to check if a string is valid json before trying to parse it?

For example getting some information from some other urls, sometimes it returns json, sometimes it could return a garbage which is not a valid response.

My code:

def get_parsed_response(response)
  parsed_response = JSON.parse(response)
end

Ruby Solutions


Solution 1 - Ruby

You can create a method to do the checking:

def valid_json?(json)
    JSON.parse(json)
    return true
  rescue JSON::ParserError => e
    return false
end

Solution 2 - Ruby

You can parse it this way

begin
  JSON.parse(string)  
rescue JSON::ParserError => e  
  # do smth
end 
 
# or for method get_parsed_response
 
def get_parsed_response(response)
  parsed_response = JSON.parse(response)
rescue JSON::ParserError => e  
  # do smth
end

Solution 3 - Ruby

I think parse_json should return nil if it's invalid and shouldn't error out.

def parse_json string
  JSON.parse(string) rescue nil
end

unless json = parse_json string
  parse_a_different_way
end

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSamView Question on Stackoverflow
Solution 1 - RubyRicha SinhaView Answer on Stackoverflow
Solution 2 - RubygotvaView Answer on Stackoverflow
Solution 3 - Rubystevo999999View Answer on Stackoverflow