最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to check if a json string is valid or not in JavaScript or Jquery? - Stack Overflow

programmeradmin1浏览0评论

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) returns true. – Jeremy Thille Commented Aug 16, 2016 at 10:17
  • Yeah you were right Jeremy Thille – Tom Taylor Commented Aug 16, 2016 at 11:03
Add a ment  | 

2 Answers 2

Reset to default 8

To 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;
}
发布评论

评论列表(0)

  1. 暂无评论