How can I check if a value is a json object?

后端 未结 13 1428
-上瘾入骨i
-上瘾入骨i 2020-11-30 23:33

My server side code returns a value which is a json object on success and a string \'false\' on failure. Now how can I check whether the returned value is a json object?

相关标签:
13条回答
  • var checkJSON = function(m) {
    
       if (typeof m == 'object') { 
          try{ m = JSON.stringify(m); }
          catch(err) { return false; } }
    
       if (typeof m == 'string') {
          try{ m = JSON.parse(m); }
          catch (err) { return false; } }
    
       if (typeof m != 'object') { return false; }
       return true;
    
    };
    
    
    checkJSON(JSON.parse('{}'));      //true
    checkJSON(JSON.parse('{"a":0}')); //true
    checkJSON('{}');                  //true
    checkJSON('{"a":0}');             //true
    checkJSON('x');                   //false
    checkJSON('');                    //false
    checkJSON();                      //false
    
    0 讨论(0)
  • 2020-11-30 23:45

    I don't really like the accepted answer. First and foremost it requires jQuery, which is not always available or required. Secondly, it does a full stringification of the object which to me is overkill. Here's a simple function that thoroughly detects whether a value is JSON-like, using nothing more than a few parts of the lodash library for genericity.

    import * as isNull from 'lodash/isNull'
    import * as isPlainObject from 'lodash/isPlainObject'
    import * as isNumber from 'lodash/isNumber'
    import * as isBoolean from 'lodash/isBoolean'
    import * as isString from 'lodash/isString'
    import * as isArray from 'lodash/isArray'
    
    function isJSON(val) {
      if (isNull(val)
       || isBoolean(val)
       || isString(val))
        return true;
      if (isNumber(val)) 
         return !isNaN(val) && isFinite(val)
      if (isArray(val))
        return Array.prototype.every.call(val, isJSON)
      if (isPlainObject(val)) {
        for (const key of Object.keys(val)) {
          if (!isJSON(val[key]))
            return false
        }
        return true
      }
      return false
    }
    

    I've even taken the time to put it up in npm as a package: https://npmjs.com/package/is-json-object. Use it together with something like Webpack to get it in the browser.

    Hope this helps someone!

    0 讨论(0)
  • 2020-11-30 23:47

    If you have jQuery, use isPlainObject.

    if ($.isPlainObject(my_var)) {}
    
    0 讨论(0)
  • 2020-11-30 23:50

    jQuery.parseJSON() should return an object of type "object", if the string was JSON, so you only have to check the type with typeof

    var response=jQuery.parseJSON('response from server');
    if(typeof response =='object')
    {
      // It is JSON
    }
    else
    {
      if(response ===false)
      {
         // the response was a string "false", parseJSON will convert it to boolean false
      }
      else
      {
        // the response was something else
      }
    }
    
    0 讨论(0)
  • 2020-11-30 23:51

    You should return json always, but change its status, or in following example the ResponseCode property:

    if(callbackResults.ResponseCode!="200"){
        /* Some error, you can add a message too */
    } else {
        /* All fine, proceed with code */
    };
    
    0 讨论(0)
  • 2020-11-30 23:56

    I am using this to validate JSON Object

    function isJsonObject(obj) {
        try {
            JSON.parse(JSON.stringify(obj));
        } catch (e) {
            return false;
        }
        return true;
    }
    

    I am using this to validate JSON String

    function isJsonString(str) {
        try {
            JSON.parse(str);
        } catch (e) {
            return false;
        }
        return true;
    }
    
    0 讨论(0)
提交回复
热议问题