如果要对JSON进行格式化验证,请利用kwalify。
如附件的一个JSON,要对其做格式化校验,请参考代码:
require 'kwalify'
require 'json'
require 'ostruct'
def h2o(x)
x.is_a?(Hash) ?
OpenStruct.new(x.keys.each_with_object({}) { |e, h|
h[e] = h2o(x[e])
}) :
x
end
schema_json = Kwalify::Yaml.load_file('scheme.json')
validator = Kwalify::Validator.new(schema_json)
parser = Kwalify::Yaml::Parser.new(validator)
document = parser.parse_file('1.json')
geoptima = h2o(document).geoptima
puts geoptima
errors = parser.errors()
if errors && !errors.empty?
for e in errors
puts "[#{e.path}] #{e.message}"
end
end