【问题标题】:nodejs json-schema fail to read schemanodejs json-schema 无法读取架构
【发布时间】:2012-10-11 18:13:08
【问题描述】:

我有一个 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}' } ]

【问题讨论】:

  • 他们是如何失败的? IE。您遇到了什么错误?
  • @jsalonen 我添加了输入和输出
  • 看起来你正在向验证器传递一个字符串,它应该是 JSON。查看 json-schema 项目中的测试,您可以看到它们在调用 validate 之前使用了 JSON.parse(str)。 github.com/kriszyp/json-schema/blob/master/test/tests.js

标签: json node.js rest express jsonschema


【解决方案1】:

如错误所示,您的架构无效。架构也应该是有效的 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');

【讨论】:

    猜你喜欢
    • 2015-11-01
    • 2019-08-19
    • 2014-12-04
    • 2015-06-10
    • 2021-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-17
    相关资源
    最近更新 更多