Skip to content

Instantly share code, notes, and snippets.

@crosstyan
Last active June 27, 2020 10:36
Show Gist options
  • Save crosstyan/d7a979d4903e88281d753600967461ed to your computer and use it in GitHub Desktop.
Save crosstyan/d7a979d4903e88281d753600967461ed to your computer and use it in GitHub Desktop.
A gist using ajv to verify JSON
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