json - Nodejs json-schema 无法读取架构

标签 json node.js rest express jsonschema

我有一个express应用程序,它有一个post方法(post是json类型):

server.js(简化版):

   app.post('/listener/v1/event/', function(req, res) {
            .
            .
            var event = req.body;
            var validator = require("./validator");
            validator.validate(event);
    }

validator.js 包含 json 的验证:

var jsonschemavalidate = require("json-schema");
var basicSchema = require('fs').readFileSync('./schema.json', 'utf8');

exports.validate = function (event) {
    console.log(jsonschemavalidate.validate(event, basicSchema).errors);
}

schema.json:

{ 
    name : "test",
    type : 'object', 
    properties : { 
        event_id : { type : 'string' }, 
        timestamp : { type : 'string' } 
    }
}

对于输入,我使用curl:

curl -i -X POST -H 'Content-Type: application/json' -d '{"event_id": "NedaleGassss", "timestamp": "a2009321"}' http://localhost:3000/listener/v1/event/

输出如下:

[ { property: '',
    message: 'Invalid schema/property definition {\n    name : "test",\n    type : "object",\n    additionalProperties : false,\n    properties :\n    {\n        event_id            : { type : "string" },\n        timestamp        \t: { type : "string" }\n    }\n}' } ]

最佳答案

正如错误所示,您的架构无效。模式也应该是有效的 JSON, 所以属性和字符串应该用双引号引起来:

{ 
  "name" : "test",
  "type" : "object", 
  "properties"  : { 
    "event_id"  : { "type" : "string" }, 
    "timestamp" : { "type" : "string" } 
  }
}

这应该可以解决问题,(除非你在过去的一年里已经弄清楚了)

还有:

var basicSchema = require('fs').readFileSync('./schema.json', 'utf8');

可能会被替换为:

var basicSchema = require('./schema');

关于json - Nodejs json-schema 无法读取架构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13002898/

相关文章:

wcf - 可以同时以JSON(P)和XML响应并且仍用作SOAP Web服务的RESTful WCF服务吗?

jquery - 如何通过 jQuery 获取 GitHub 存储库上最新提交的 SHA?

javascript - Node.js 中使用 BodyParser 解析 JSON 嵌套对象

python - 找不到 Python 可执行文件 "python"

rest - Tapestry + REST

arrays - Ansible 解析来自 Register 的 JSON 数组

java - 在 Jackson 中将对象序列化为 JSON,无需根 key

javascript - Grunt 文件对象格式 : All regular files files immediately under top level directory

java - Jersey、JAXB、JAX-RS、Moxy、Jackson、EclipseLink Moxy、json 和 xml 之间有什么关系?

java - org.glassfish.jersey.internal.RuntimeDelegateImpl 未找到