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

后端 未结 13 1465
-上瘾入骨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条回答
  •  醉酒成梦
    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!

提交回复
热议问题