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

JqueryJsonObject

Jquery Problem Overview


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?

Jquery Solutions


Solution 1 - Jquery

The chosen solution doesn't actually work for me because I get a

     "Unexpected Token <" 

error in Chrome. This is because the error is thrown as soon as the parse comes across and unknown character. However, there is a way around this if you are returning only string values through ajax (which can be fairly useful if you are using PHP or ASPX to process ajax requests and might or might not return JSON depending on conditions)

The solution is quite simple, you can do the following to check if it was a valid JSON return

       var IS_JSON = true;
       try
       {
               var json = $.parseJSON(msg);
       }
       catch(err)
       {
               IS_JSON = false;
       }                

As I have said before, this is the solution for if you are either returning string type stuff from your AJAX request or if you are returning mixed type.

Solution 2 - Jquery

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
  }
}

Solution 3 - Jquery

Solution 3 (fastest way)
/**
 * @param Object
 * @returns boolean
 */
function isJSON (something) {
    if (typeof something != 'string')
        something = JSON.stringify(something);

    try {
        JSON.parse(something);
        return true;
    } catch (e) {
        return false;
    }
}

You can use it:

var myJson = [{"user":"chofoteddy"}, {"user":"bart"}];
isJSON(myJson); // true


The best way to validate that an object is of type JSON or array is as follows:

var a = [],
    o = {};
Solution 1
toString.call(o) === '[object Object]'; // true
toString.call(a) === '[object Array]'; // true
Solution 2
a.constructor.name === 'Array'; // true
o.constructor.name === 'Object'; // true

But, strictly speaking, an array is part of a JSON syntax. Therefore, the following two examples are part of a JSON response:

console.log(response); // {"message": "success"}
console.log(response); // {"user": "bart", "id":3}

And:

console.log(response); // [{"user":"chofoteddy"}, {"user":"bart"}]
console.log(response); // ["chofoteddy", "bart"]


If you use JQuery to bring information via AJAX. I recommend you put in the "dataType" attribute the "json" value, that way if you get a JSON or not, JQuery validate it for you and make it known through their functions "success" and "error". Example:

$.ajax({
    url: 'http://www.something.com',
    data: $('#formId').serialize(),
    method: 'POST',
    dataType: 'json',
    // "sucess" will be executed only if the response status is 200 and get a JSON
    success: function (json) {},
    // "error" will run but receive state 200, but if you miss the JSON syntax
    error: function (xhr) {}
});

Solution 4 - Jquery

If you have jQuery, use isPlainObject.

if ($.isPlainObject(my_var)) {}

Solution 5 - Jquery

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

Solution 6 - Jquery

Since it's just false and json object, why don't you check whether it's false, otherwise it must be json.

if(ret == false || ret == "false") {
    // json
}

Solution 7 - Jquery

I know this thread has been answered already, but coming here didn't really solve my problems, I found this function somewhere else. maybe someone coming here will find it to be of some use to them;

function getClass(obj) {
  if (typeof obj === "undefined")
    return "undefined";
  if (obj === null)
    return "null";
  return Object.prototype.toString.call(obj)
    .match(/^\[object\s(.*)\]$/)[1];
}

Solution 8 - Jquery

var data = 'json string ?';
var jdata = null;
try
{
	jdata = $.parseJSON(data);	
}catch(e)
{}

if(jdata)
{
//use jdata
}else
{
//use data
}

Solution 9 - Jquery

If you want to test explicitly for valid JSON (as opposed to the absence of the returned value false), then you can use a parsing approach as described here.

Solution 10 - Jquery

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!

Solution 11 - Jquery

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;
}

Solution 12 - Jquery

i tried all of the suggested answers, nothing worked for me, so i had to use

jQuery.isEmptyObject()

hoe that helps someone else out with this issue

Solution 13 - Jquery

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 */
};

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionbartView Question on Stackoverflow
Solution 1 - JquerySerguei FedorovView Answer on Stackoverflow
Solution 2 - JqueryDr.MolleView Answer on Stackoverflow
Solution 3 - JqueryChofoteddyView Answer on Stackoverflow
Solution 4 - JquerythneeView Answer on Stackoverflow
Solution 5 - JqueryluizhpView Answer on Stackoverflow
Solution 6 - JqueryAndreas WongView Answer on Stackoverflow
Solution 7 - Jquerypythonian29033View Answer on Stackoverflow
Solution 8 - JqueryFiras Abd AlrahmanView Answer on Stackoverflow
Solution 9 - JqueryKen RedlerView Answer on Stackoverflow
Solution 10 - JquerysamvvView Answer on Stackoverflow
Solution 11 - JqueryAbhishek GoelView Answer on Stackoverflow
Solution 12 - JqueryJay RizziView Answer on Stackoverflow
Solution 13 - JquerykobeView Answer on Stackoverflow