How to check if it's a string or json [duplica

2020-02-05 06:25发布

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

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

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

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'));

5条回答
Melony?
2楼-- · 2020-02-05 07:12

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

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 isValid is true only for objects (e.g: { "key": "value" }) and arrays (e.g: [{ "key": "value" }]) you can use following version:

function tryParse(str) {
    try {
        var parsed = JSON.parse(str);
        return { value: parsed , isValid: typeof parsed === 'object'}
    } catch (e) {
        return { value: str, isValid: false }
    }
}
查看更多
成全新的幸福
3楼-- · 2020-02-05 07:17

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

var data = localStorage[key];
try {return JSON.parse(data);}
catch(e) {return data;}
查看更多
SAY GOODBYE
4楼-- · 2020-02-05 07:17

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

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;
}
查看更多
▲ chillily
5楼-- · 2020-02-05 07:21

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

function isJSON(data) {
   var ret = true;
   try {
      JSON.parse(data);
   }catch(e) {
      ret = false;
   }
   return ret;
}
查看更多
孤傲高冷的网名
6楼-- · 2020-02-05 07:23

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:

    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.

查看更多
登录 后发表回答