jQuery 如何检查它是字符串还是json

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18745406/
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 22:23:38  来源:igfitidea点击:

How to check if it's a string or json

javascriptjqueryjson

提问by crzyonez777

I have a json string that is converted from object by JSON.Stringify function.

我有一个由 JSON.Stringify 函数从对象转换而来的 json 字符串。

I'd like to know if it's json string or just a regular string.

我想知道它是 json 字符串还是只是一个普通字符串。

Is there any function like "isJson()" to check if it's json or not?

有没有像“isJson()”这样的函数来检查它是否是json?

I'd like to use the function when I use local storage like the code below.

当我像下面的代码一样使用本地存储时,我想使用该功能。

Thank you in advance!!

先感谢您!!

var Storage = function(){}

Storage.prototype = {

  setStorage: function(key, data){

    if(typeof data == 'object'){

      data = JSON.stringify(data);
      localStorage.setItem(key, data);     

    } else {
      localStorage.setItem(key, data);
    }

  },


  getStorage: function(key){

    var data = localStorage.getItem(key);

    if(isJson(data){ // is there any function to check if the argument is json or string?

      data = JSON.parse(data);
      return data;

    } else {

      return data;
    }

  }

}

var storage = new Storage();

storage.setStorage('test', {x:'x', y:'y'});

console.log(storage.getStorage('test'));

回答by Niet the Dark Absol

The "easy" way is to tryparsing and return the unparsed string on failure:

“简单”的方法是try解析并在失败时返回未解析的字符串:

var data = localStorage[key];
try {return JSON.parse(data);}
catch(e) {return data;}

回答by letiagoalves

you can easily make one using JSON.parse. When it receives a not valid JSON string it throws an exception.

您可以轻松地使用JSON.parse. 当它收到无效的 JSON 字符串时,它会引发异常。

function isJSON(data) {
   var ret = true;
   try {
      JSON.parse(data);
   }catch(e) {
      ret = false;
   }
   return ret;
}

回答by Benoit Gauthier

Found this in another post How do you know if an object is JSON in javascript?

在另一篇文章中找到了这个你如何知道一个对象是否是 javascript 中的 JSON?

function isJSON(data) {
    var isJson = false
    try {
        // this works with JSON string and JSON object, not sure about others
       var json = $.parseJSON(data);
       isJson = typeof json === 'object' ;
    } catch (ex) {
        console.error('data is not JSON');
    }
    return isJson;
}

回答by darmis

Since the question is "How to check if it's a string or json" maybe a simple way would be to check for string, so you would have done something like this somewhere:

由于问题是“如何检查它是字符串还是 json”,因此检查字符串可能是一种简单的方法,因此您可以在某处执行以下操作:

    if (typeof data === 'string') { // check for string!
      //... do something
    } else {///... do something else}

Maybe that could be enough depending on your overall solution, just in case someone else is looking around.

也许这可能就足够了,这取决于您的整体解决方案,以防其他人四处张望。

回答by Mehdi Dehghani

I think returning parsed JSON at the same time is a good idea, so I prefer following version:

我认为同时返回解析的 JSON 是个好主意,所以我更喜欢以下版本:

function tryParse(str) {
    try {
        return { value: JSON.parse(str), isValid: true }
    } catch (e) {
        return { value: str, isValid: false }
    }
}

As you probably know JSON.parse("1234"), JSON.parse("0"), JSON.parse("false")and JSON.parse("null")won't raise Exception and will return true. all this values are valid JSON but if you want to see isValidis trueonly for objects (e.g: { "key": "value" }) and arrays (e.g: [{ "key": "value" }]) you can use following version:

正如你可能知道JSON.parse("1234")JSON.parse("0")JSON.parse("false")JSON.parse("null")不会引发异常,将返回true。所有这些值是有效的JSON,但如果你希望看到的isValidtrue只为对象(例如:{ "key": "value" })和阵列(例如:[{ "key": "value" }]),可以使用以下版本:

function tryParse(str) {
    try {
        var parsed = JSON.parse(str);
        return { value: parsed , isValid: typeof parsed === 'object'}
    } catch (e) {
        return { value: str, isValid: false }
    }
}