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

标签 javascript jquery json

<分区>

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

我想知道它是 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'));

最佳答案

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

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

关于javascript - 如何检查它是字符串还是json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18745406/

相关文章:

javascript - 更改背景图像 - javascript

javascript - ASP.NET:如何更新 JQuery 或 Javascript 中的隐藏字段?

java - 需要 GSON 返回一个 Java JSONArray

python - Pyramid :从列表生成 json View

python - 使用 Python 将 JSON 对象导入 Postgresql

javascript - 为什么 UUID 不能只是带有序列号的时间戳?

javascript - setInterval 永远不会在函数中触发,并且不知道为什么( Angular )

javascript - 用户通过&lt;input type ="file"/>选择文件时如何获取文件名?

jquery - 背景图像显示在弹出消息上

javascript - 使用 jQuery 从原始页面内容创建 iframe