How to validate if a string is json in a Rails model

I suppose you could parse the field in question and see if it throws an error. Here’s a simplified example (you might want to drop the double bang for something a bit clearer):

require 'json'

class String
  def is_json?
    begin
      !!JSON.parse(self)
    rescue
      false
    end
  end
end

Then you could use this string extension in a custom validator.

validate :json_format

protected

  def json_format
    errors[:base] << "not in json format" unless json.is_json?
  end

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)