Comment vérifier si c’est une chaîne ou un json

J’ai une chaîne JSON qui est convertie d’object par la fonction JSON.Ssortingngify.

J’aimerais savoir s’il s’agit d’une chaîne json ou d’une chaîne normale.

Existe-t-il une fonction telle que “isJson ()” pour vérifier si c’est json ou non?

J’aimerais utiliser cette fonction lorsque j’utilise un stockage local, comme le code ci-dessous.

Merci d’avance!!

var Storage = function(){} Storage.prototype = { setStorage: function(key, data){ if(typeof data == 'object'){ data = JSON.ssortingngify(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 ssortingng? 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')); 

La méthode “facile” consiste à try parsing et à renvoyer la chaîne non analysée en cas d’échec:

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

vous pouvez facilement en créer un en utilisant JSON.parse . Lorsqu’il reçoit une chaîne JSON non valide, il lève une exception.

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

Trouvé ceci dans un autre article Comment savoir si un object est JSON en javascript?

 function isJSON(data) { var isJson = false try { // this works with JSON ssortingng 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; }