如何检查值是否是 JSON 对象?

我的服务器端代码在成功时返回一个值,失败时返回一个字符串‘ false’。现在如何检查返回的值是否是 JSON 对象?

226674 次浏览

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

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
}

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.

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

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.

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];
}
var data = 'json string ?';
var jdata = null;
try
{
jdata = $.parseJSON(data);
}catch(e)
{}


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

If you have jQuery, use isPlainObject.

if ($.isPlainObject(my_var)) {}

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"]

AJAX / JQuery (recommended)

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

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!

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

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