Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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'));
like image 260
crzyonez777 Avatar asked Sep 11 '13 15:09

crzyonez777


People also ask

How do I know if my data is JSON or string?

If you have var a = 1 and var var b = "1" then typeof a is number and typeof b is string , both a and b can be passed to JSON. parse and it would result in 1 , but only b is in this case JSON, because it is a string based representation of the number 1 .

How do you check if a string is a JSON string?

To check if a string is JSON in JavaScript, we can use the JSON. parse method within a try-catch block. to check if jsonStr is a valid JSON string. Since we created the JSON string by calling JSON.

Is JSON object or string?

JSON is purely a string with a specified data format — it contains only properties, no methods. JSON requires double quotes to be used around strings and property names.

Can JSON have duplicate key?

We can have duplicate keys in a JSON object, and it would still be valid.


1 Answers

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;}
like image 181
Niet the Dark Absol Avatar answered Oct 08 '22 01:10

Niet the Dark Absol