比较具有json模式的对象,如果未设置,则使用模式默认值填充它

问题描述 投票:0回答:1

我正在使用Ruby JSON Schema Validator验证我的一些输入数据,这非常好。

但是我想更新输入数据,以便在未设置模式值的情况下采用模式的默认值。

  input = {'url' => 'http://www.google.com'}

  schema = {
    "type": "object",
    "properties": {
      "url": {
        "type": "string",
      },
      "infos":{
        "type": "object",
        "properties": {
          "content_type": {
            "type": "string",
            "default": "html",
          },
        }
      }
    }
  }

  #make some magic here to update my input with the schema

  output = {
      'url' => 'http://www.google.com',
      'infos' => {'content_type'=>'html'}
  }

知道输入的结构与模式之一不一样,我怎么能做到这一点?

Ruby JSON Schema Validator中有一个:insert_defaults选项,但是我看不到检索填充对象的方法。似乎与此相关的代码是here

我也搜索过Google,并尝试过使用[[deep_merge(),但是由于要比较的结构并不相同,因此我不知道该如何处理。

json ruby validation jsonschema
1个回答
0
投票
这是我想出的:

def defaultsFromSchema(node,nodekeys=[],datas={}) return unless node.is_a?(Hash) if node.has_key?('default') value = node['default'] #create hash and set deep keys return nodekeys.reverse.inject(value) { |a, n| { n => a } } else node.each do |k, v| keys = nodekeys.clone if k != 'properties' keys.push(k) end append = defaultsFromSchema(v,keys,datas) if append datas = datas.deep_merge(append) end end end datas end

© www.soinside.com 2019 - 2024. All rights reserved.