I saw this
if (value[0] == "{")
I don’t really like this option. Is there another way? Here's what I thought up myself: do a check through the object
typeof(JSON.parse(value))=='object'.
So fit?
I saw this
if (value[0] == "{")
I don’t really like this option. Is there another way? Here's what I thought up myself: do a check through the object
typeof(JSON.parse(value))=='object'.
So fit?
Here is the same question on StackOverflow . Two solutions, via JSON.parse ()
function IsJsonString(str) { try { JSON.parse(str); } catch (e) { return false; } return true; }
and through the regular season:
if (/^[\],:{}\s]*$/.test(text.replace(/\\["\\\/bfnrtu]/g, '@'). replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']'). replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { //the json is ok }else{ //the json is not ok }
I propose such a parser function that I usually use. It solves the problem with IE
function parseJSON(parJSON) { //если переданный параметр - строка (а то мало ли) if(typeof parJSON == "string"){ //начинаем парсит JSON return window.JSON && window.JSON.parse ? JSON.parse(parJSON) : eval('('+parJSON+')'); //если браузер поддерживает встроенный JSON, то используем его. Если нет (IE6-7) то используем eval } return parJSON; }
"And why do you have to check this out? You have architecture problems. When you get a string, you should already know what format it is, and not find out for yourself.
I can give an example from practice. With qr-code comes json. So, the user can create his own qr-code and don’t submit json to the input. Therefore! The problem is relevant and you can not immediately draw a conclusion about the architecture of the project.
Source: https://ru.stackoverflow.com/questions/204274/
All Articles