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

crz*_*777 15 javascript jquery json

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

我想知道它是json字符串还是只是一个常规字符串.

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

当我使用本地存储时,我想使用该功能,如下面的代码.

先感谢您!!

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'));
Run Code Online (Sandbox Code Playgroud)

Nie*_*sol 31

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

var data = localStorage[key];
try {return JSON.parse(data);}
catch(e) {return data;}
Run Code Online (Sandbox Code Playgroud)


let*_*ves 14

你可以轻松地使用它JSON.parse.当它收到一个无效的JSON字符串时,它会抛出一个异常.

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


Ben*_*ier 5

在另一篇文章中发现这个如何知道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;
}
Run Code Online (Sandbox Code Playgroud)