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?

推荐答案

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

然后可以在自定义验证器中使用此字符串扩展名.

validate :json_format

protected

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

Json相关问答推荐

将json数组反序列化为选项 struct

Golang JSON Date Tim.Date()测试请求

在Jenkins中使用ReadJSON读取json子元素

当有2个嵌套数组时展平复杂的JSON

如何避免解析 ISuperObject 类型字段中的 json 对象

如何将属性拆分为嵌套的JSON内容?

遍历 JSON,检索父值

在这种情况下我如何实现 UnmarshalJSON 并且只为一个接口字段定义特殊行为?

NiFi 使用嵌套数组将 avro 转换为 JSON 数组格式

用于遮蔽卡的 Jolt 规格

如何从条带订阅响应对象中正确获取 struct 项?

JOLT 转换 - 删除 JSON 数组中的空 node

Go - JSON 验证抛出错误,除非我在 struct 中使用指针.为什么?

Angularjs访问本地json文件

如何将任意 json 对象发布到 webapi

一起使用 Argparse 和 Json

json.dumps 打乱了顺序

如何在 Java 中将 YAML 转换为 JSON?

如何将 mysqli 结果转换为 JSON?

log4j 支持 JSON 格式吗?