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

前端 未结 7 794
悲&欢浪女
悲&欢浪女 2021-01-31 16:03

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

7条回答
  •  忘了有多久
    2021-01-31 16:39

    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
    

提交回复
热议问题