admin 管理员组文章数量: 1086019
Have tried :
function isJSON(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
To check weather a string is json or not. It returns true for boolean type formats.
Is there any possible way to identify a valid json string in Java Script or in JQuery?
Have tried :
function isJSON(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
To check weather a string is json or not. It returns true for boolean type formats.
Is there any possible way to identify a valid json string in Java Script or in JQuery?
Share Improve this question edited Aug 16, 2016 at 10:37 rdubya 2,9161 gold badge17 silver badges21 bronze badges asked Aug 16, 2016 at 10:14 Tom TaylorTom Taylor 3,5802 gold badges41 silver badges72 bronze badges 3- what do you mean by boolean type formats? – Daniel A. White Commented Aug 16, 2016 at 10:16
-
He means
isJSON(false)
returnstrue
. – Jeremy Thille Commented Aug 16, 2016 at 10:17 - Yeah you were right Jeremy Thille – Tom Taylor Commented Aug 16, 2016 at 11:03
2 Answers
Reset to default 8To assure you have a valid json you must have a string first
function isJSON(str) {
if( typeof( str ) !== 'string' ) {
return false;
}
try {
JSON.parse(str);
return true;
} catch (e) {
return false;
}
}
Your function works, just add a boolean check :
function isJSON(str) {
if(typeof(str) === "boolean"){ return false; } // or if(typeof(str) !== "string")
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
本文标签: How to check if a json string is valid or not in JavaScript or JqueryStack Overflow
版权声明:本文标题:How to check if a json string is valid or not in JavaScript or Jquery? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.roclinux.cn/p/1744008736a2517759.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论