How to check if a string is a valid JSON string in JavaScript without using Try/Catch

前端 未结 24 1780
暖寄归人
暖寄归人 2020-11-22 07:50

Something like:

var jsonString = \'{ \"Id\": 1, \"Name\": \"Coke\" }\';

//should be true
IsJsonString(jsonString);

//should be false
IsJsonString(\"foo\");         


        
相关标签:
24条回答
  • 2020-11-22 08:17

    Here my working code:

    function IsJsonString(str) {
      try {
        var json = JSON.parse(str);
        return (typeof json === 'object');
      } catch (e) {
        return false;
      }
    }
    
    0 讨论(0)
  • 2020-11-22 08:19
    // vanillaJS
    function isJSON(str) {
        try {
            return (JSON.parse(str) && !!str);
        } catch (e) {
            return false;
        }
    }
    

    Usage: isJSON({}) will be false, isJSON('{}') will be true.

    To check if something is an Array or Object (parsed JSON):

    // vanillaJS
    function isAO(val) {
        return val instanceof Array || val instanceof Object ? true : false;
    }
    
    // ES2015
    var isAO = (val) => val instanceof Array || val instanceof Object ? true : false;
    

    Usage: isAO({}) will be true, isAO('{}') will be false.

    0 讨论(0)
  • 2020-11-22 08:19
    function get_json(txt)
    {  var data
    
       try     {  data = eval('('+txt+')'); }
       catch(e){  data = false;             }
    
       return data;
    }
    

    If there are errors, return false.

    If there are no errors, return json data

    0 讨论(0)
  • 2020-11-22 08:19

    For people who like the .Net convention of "try" functions that return a boolean and handle a byref param containing the result. If you don't need the out parameter you can omit it and just use the return value.

    StringTests.js

      var obj1 = {};
      var bool1 = '{"h":"happy"}'.tryParse(obj1); // false
      var obj2 = {};
      var bool2 = '2114509 GOODLUCKBUDDY 315852'.tryParse(obj2);  // false
    
      var obj3 = {};
      if('{"house_number":"1","road":"Mauchly","city":"Irvine","county":"Orange County","state":"California","postcode":"92618","country":"United States of America","country_code":"us"}'.tryParse(obj3))
        console.log(obj3);
    

    StringUtils.js

    String.prototype.tryParse = function(jsonObject) {
      jsonObject = jsonObject || {};
      try {
        if(!/^[\[{]/.test(this) || !/[}\]]$/.test(this)) // begin / end with [] or {}
          return false; // avoid error handling for strings that obviously aren't json
        var json = JSON.parse(this);
        if(typeof json === 'object'){
          jsonObject.merge(json);
          return true;
        }
      } catch (e) {
        return false;
      }
    }
    

    ObjectUtils.js

    Object.defineProperty(Object.prototype, 'merge', {
      value: function(mergeObj){
        for (var propertyName in mergeObj) {
          if (mergeObj.hasOwnProperty(propertyName)) {
            this[propertyName] = mergeObj[propertyName];
          }      
        }
        return this;
      },
      enumerable: false, // this is actually the default
    });
    
    0 讨论(0)
  • 2020-11-22 08:23

    I infer from the opening comment that the use case is delineating whether a response is HTML or JSON. In which case, when you do receive JSON, you probably ought to be parsing it and handling invalid JSON at some point in your code anyway. Aside from anything, I imagine you would like to be informed by your browser should JSON be expected but invalid JSON received (as will users by proxy of some meaningful error message)!

    Doing a full regex for JSON is unnecessary therefore (as it would be - in my experience - for most use-cases). You would probably be better off using something like the below:

    function (someString) {
      // test string is opened with curly brace or machine bracket
      if (someString.trim().search(/^(\[|\{){1}/) > -1) {
        try { // it is, so now let's see if its valid JSON
          var myJson = JSON.parse(someString);
          // yep, we're working with valid JSON
        } catch (e) {
          // nope, we got what we thought was JSON, it isn't; let's handle it.
        }
      } else {
        // nope, we're working with non-json, no need to parse it fully
      }
    }
    

    that should save you having to exception handle valid non-JSON code and take care of duff json at the same time.

    0 讨论(0)
  • 2020-11-22 08:23
    if(resp) {
        try {
            resp = $.parseJSON(resp);
            console.log(resp);
        } catch(e) {
            alert(e);
        }
    }
    

    hope this works for you too

    0 讨论(0)
提交回复
热议问题