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

前端 未结 7 664
悲&欢浪女
悲&欢浪女 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:59

    The best way is to add a method to the JSON module !

    Put this in your config/application.rb :

    module JSON
      def self.is_json?(foo)
        begin
          return false unless foo.is_a?(String)
          JSON.parse(foo).all?
        rescue JSON::ParserError
          false
        end 
      end
    end
    

    Now you'll be enable to use it anywhere ('controller, model, view,...'), just like this :

    puts 'it is json' if JSON.is_json?(something)
    
    0 讨论(0)
提交回复
热议问题