jQuery 如何检查值是否为 json 对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4295386/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:00:54  来源:igfitidea点击:

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

jqueryjsonobject

提问by bart

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?

我的服务器端代码返回一个值,它是成功时的 json 对象和失败时的字符串“false”。现在如何检查返回值是否为 json 对象?

回答by Serguei Fedorov

The chosen solutiondoesn'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)

Chrome 中的错误。这是因为一旦遇到解析和未知字符,就会抛出错误。但是,如果您仅通过 ajax 返回字符串值,则有一种方法可以解决此问题(如果您使用 PHP 或 ASPX 处理 ajax 请求,并且可能会或可能不会根据条件返回 JSON,这将非常有用)

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

解决方案很简单,您可以执行以下操作来检查它是否是有效的 JSON 返回

       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.

正如我之前所说,如果您从 AJAX 请求中返回字符串类型的内容或返回混合类型,这就是解决方案。

回答by Dr.Molle

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

jQuery.parseJSON() 应该返回一个“object”类型的对象,如果字符串是 JSON,那么你只需要检查类型 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
  }
}

回答by Chofoteddy

Solution 3 (fastest way)

解决方案3(最快的方式)

/**
 * @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:

验证对象是否为 JSON 或数组类型的最佳方法如下:

var a = [],
    o = {};

Solution 1

解决方案1

toString.call(o) === '[object Object]'; // true
toString.call(a) === '[object Array]'; // true

Solution 2

解决方案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:

但是,严格来说,数组是 JSON 语法的一部分。因此,以下两个示例是 JSON 响应的一部分:

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)

AJAX / JQuery(推荐)

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:

如果您使用 JQuery 通过 AJAX 带来信息。我建议您在“dataType”属性中放入“json”值,这样无论您是否获得 JSON,JQuery 都会为您验证它并通过它们的“成功”和“错误”功能使其为人所知。例子:

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

回答by thnee

If you have jQuery, use isPlainObject.

如果您有 jQuery,请使用isPlainObject

if ($.isPlainObject(my_var)) {}

回答by luizhp

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

回答by Andreas Wong

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

既然只是false和json对象,为什么不检查一下是否是false,否则肯定是json。

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

回答by pythonian29033

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

回答by Firas Abd Alrahman

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

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

回答by Ken Redler

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.

如果您想显式测试有效的 JSON(而不是没有返回值false),那么您可以使用这里描述的解析方法。

回答by samvv

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 lodashlibrary for genericity.

我真的不喜欢接受的答案。首先,它需要 jQuery,但它并不总是可用或必需的。其次,它对对象进行了完整的字符串化,这对我来说太过分了。这是一个简单的函数,它彻底检测一个值是否类似于 JSON,仅使用lodash库的几个部分来实现通用性。

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 Webpackto get it in the browser.

我什至花时间把它作为一个包放在 npm 中:https: //npmjs.com/package/is-json-object。将它与Webpack 之类的东西一起使用以在浏览器中获取它。

Hope this helps someone!

希望这可以帮助某人!