我正在使用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(),但是由于要比较的结构并不相同,因此我不知道该如何处理。
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