Jasper Kennis Jasper Kennis - 5 months ago 37
JSON Question

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

I'm building a simple app and want to be able to store json strings in a db. I have a table Interface with a column json, and I want my rails model to validate the value of the string. So something like:

class Interface < ActiveRecord::Base
attr_accessible :name, :json

validates :name, :presence => true,
:length => { :minimum => 3,
:maximum => 40 },
:uniqueness => true

validates :json, :presence => true,
:type => json #SOMETHING LIKE THIS
:contains => json #OR THIS
end


How do I do that?

Answer

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