JSON Validator
JSON Validator
XML表达信息比较详尽,格式清晰。其实做代码的generator等脚本的时候,也会通过JSON来传递用户的定制参数的。比如cfg.json的内容如下:
{
"timescale":"1ns/1ps",
"dut":{
"name":"mydut",
"top_file":"~/mydut.v",
"filelist":"~/mydut.f"
},
"tbp":"demo",
"env":{
"name":"bus",
"agent":[
{
"name":"abc",
"active":1,
"off":0,
"interface":{
"ifclk":"clk",
"ifrst":"rst",
"signal":[
{
"name":"ahb_burst",
"bind":"ahb_burst_o"
},
{
"name":"ahb_valid",
"bind":"ahb_valid_o"
}
]
}
}
]
}
}
同样的,如何在第一时间去check用户输入的json信息是否是正确的?这时候就用到了json-schema文件作为一种validation的标准。假设top.schema.json的内容如下:
{
"type": "object",
"properties":{
"timescale":{
"type": "string"
},
"dut":{
"type":"object",
"properties":{
"name":{
"type":"string"
},
"top_file":{
"type":"string"
},
"filelist":{
"type":"string"
}
},
"required":["name","top_file","filelist"]
},
"env":{
"type":"object",
"properties":{
"name":{
"type":"string"
},
"agent":{
"type":"array",
"items":{
"type":"object",
"properties":{
"name":{
"type":"string"
},
"active":{
"type":"integer"
},
"off":{
"type":"integer"
},
"interface":{
"type":"object",
"properties":{
"ifclk":{
"type":"string"
},
"ifrst":{
"type":"string"
},
"signal":{
"type":"array",
"items":{
"type":"object",
"properties":{
"name":{
"type":"string"
},
"bind":{
"type":"string"
}
},
"required":["name"]
},
"minItems":1
}
},
"required":["signal"]
}
},
"required":["name"]
},
"minItems":1
}
}
}
},
"required":["dut"]
}
我们用perl来处理JSON文件的validation过程,如下:
use JSON qw(decode_json);
use JSON::Validator qw(validate_json);
my $validator = JSON::Validator->new;
open(FILE, "top.schema.json") or die "Can not open file top.schema.json";
my @lines = <FILE>;
my $schema = decode_json(join("\n",@lines));
close(FILE);
$validator->schema($schema);
open(FILE, "cfg.json") or die "Can not open file cfg.json";
@lines = <FILE>;
close(FILE);
my $json_to_be_validated = decode_json(join("\n",@lines));
# Validate your data
@errors = $validator->validate($json_to_be_validated);
# Do something if any errors was found
die "@errors" if @errors;
通过对比可以发现虽然json数据格式简单,但是json的validation格式很不友好,比XML的DTD格式杂乱的多。