Skip to content

Instantly share code, notes, and snippets.

@Jason-cqtan
Created July 11, 2019 03:48
Show Gist options
  • Save Jason-cqtan/7ed007a93e52fbac562d95e6848ab3da to your computer and use it in GitHub Desktop.
Save Jason-cqtan/7ed007a93e52fbac562d95e6848ab3da to your computer and use it in GitHub Desktop.
判断字符串是否json字符串
if(typeof str == 'string'){
try{
var obj = JSON.parse(str);
return !!obj && typeof obj === 'object';
}catch(e){
return false;
}
}
@Jason-cqtan
Copy link
Author

需考虑
JSON.parse('123'); // 123
JSON.parse('{}'); // {}
JSON.parse('true'); // true
JSON.parse('"foo"'); // "foo"
JSON.parse('[1, 5, "false"]'); // [1, 5, "false"]
JSON.parse('null'); // null

如有需要使用validator库

nmp install validator

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment