2016-11-24 110 views
2

我是json的新手。我在Json模式中学习了更多的东西,但是我无法依据json-schema.json文件测试我的user.json文件。请注意我需要测试一个javascript变量,它应该返回true或false来进一步处理。在此我粘贴了我的文件。如何用json模式文件测试json文件

JSON-schema.json

{ 
    "description": "Any validation failures are shown in the right-hand Messages pane.", 
    "type": "object", 
    "properties": { 
    "foo": { 
     "type": "number" 
    }, 
    "bar": { 
     "type": "string", 
     "enum": [ 
     "a", 
     "b", 
     "c" 
     ] 
    } 
    } 
} 

user.json

{ 
"foo": 12345, 
"bar": "a" 
} 

当我在http://jsonschemalint.com/#/version/draft-05/markup/json测试了上面的代码表示的user.json是正确的格式。但我需要在本地进行测试

在此先感谢。

+0

的可能的复制[?如何测试一个字符串是否是JSON或不](http://stackoverflow.com/questions/9804777/how -to-test-if-a-string-is-json-or-not) – Mahi

+0

在浏览器或应用中? – Legends

+0

在浏览器@传奇 –

回答

0

您可以使用JSON schema validators之一。使用这些库之一,ajv

实施例:

import Ajv from 'ajv'; 

import schema from 'schema.json'; 
import data from 'data.json'; 

function isValid(schema, data) { 
    const ajv = new Ajv(); 
    const valid = ajv.validate(schema, data); 

    if (!valid) { 
    console.log(ajv.errors); 
    return false; 
    } 

    return true; 
}