json schema validate

阅读更多
为了检测API返回的数据结构是否正确,刚好chrome的插件postman可以做这件事。其实它用的也是tv4的库来验证。又找了一些开源的验证工具。如下
在线验证工具:
只支持http://json-schema.org/draft-03/schema#
https://json-schema-validator.herokuapp.com/

schema
{
  "$schema": "http://json-schema.org/draft-03/schema#",
  "title": "App",
  "description": "APP LIST",
  "type": "array",  
  "properties":{
  	"appID": {
     	"type": "string",
        "required":true
     },
     "appName":{
         "type": "string",
        "required":true
      },
    "appCaption":{
         "type": "string",
        "required":true
      },
      "icon":{
        "type":"string",
 "required":true
      }
  }
}


json:
[{"appID":"1","appName":"push","appCaption":"push ","icon":""},{"appID":"52","appName":"Sample(\u4e13\u7528)","appCaption":"Sample(\u4e13\u7528)","icon":""},{"appID":"64","appName":"\u65b0\u73af\u5883\u6d4b\u8bd5dddd","appCaption":"\u65b0\u73af\u5883\u6d4b\u8bd5","icon":""}]


dojo json schema:
http://pro.jsonlint.com/








dojox.json.schema example









Example use of dojox.json.schema

Due to its use of the Dojo CDN distribution on google.com, this HTML file MUST be accessed through an HTTP server such as Apache. file:/// URIs won't work.'



在postman中的json validate
tests["Status code is 200"] = responseCode.code === 200;

var data = JSON.parse(responseBody);
tests["status"] = data.status === true;
tests["info"] = data.info === "success";
var appData = data.data;
tests['appCount'] = appData.length === 3;
var schema = {
  "$schema": "http://json-schema.org/draft-04/schema#",
  "title": "App",
  "description": "APP LIST",
  "type": "object",  
  "properties":{
  	"appID": {
     	"type": "string"
     },
     "appName":{
         "type": "string"
      },
    "appCaption":{
         "type": "string"
      },
      "icon":{
        "type":"string",
        "required":true,
        "pattern":"^http://"
      }
  }
};

$.each(appData, function (i) {
    var app = this;
  tests['appName'+i] = tv4.validate(app, schema); 
})




参考资料:
http://www.asbjornenge.com/wwc/json_schema.html
http://json-schema.org/documentation.html
postman 用的验证工具
https://github.com/geraintluff/tv4
http://www.getpostman.com/docs/

你可能感兴趣的:(json,数据结构)