Last active
June 27, 2020 10:36
-
-
Save crosstyan/d7a979d4903e88281d753600967461ed to your computer and use it in GitHub Desktop.
A gist using ajv to verify JSON
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function parsePost(yourDataStr:string) :YourClass|null{ | |
//require你所生成的schema, 不知道为什么用import的时候对json会报错, resolveJsonModule已经开了 | |
const yourSchema=require("./yourSchema") | |
const ajv = new Ajv({allErrors:true}) | |
//想要快一些应该可以先Compile罢 | |
try { | |
const yourDataJson = JSON.parse(yourDataStr) | |
const isValid = ajv.validate(yourSchema,yourDataStr) //return boolean | |
if (isValid) { | |
return yourDataJson as YourClass | |
} else { | |
return null | |
} | |
} catch{ | |
return null | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment