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

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

    The most simple and elegant way, imo. The top upvoted answers will either return true when passing a string containing integers or floats, or throw an error in this case.

    def valid_json?(string)
        hash = Oj.load(string)
        hash.is_a?(Hash) || hash.is_a?(Array)
    rescue Oj::ParseError
        false
    end
    

提交回复
热议问题