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?

  • It is not very clear what you want to do. JSON is the representation of an object as a string. Add an example of what you input to the function and what should be the output. - Zhukov Roman
  • I will say this: check that the variable is a JSON string. I can not explain more clearly. - zloctb
  • one
    Why do you have to check this out? You have architecture problems. When you get a string, you should already know in what format it is, and not find out for yourself. - VladD 4:08 pm
  • I learned for the future. I didn’t really face such a task. - zloctb

3 answers 3

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 } 
  • try..catch is a great option. Thanks - zloctb
  • try / catch decides, and only @ReinRaus is able to emulate the parser with a regular program on this site. - VladD 4:05 pm

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; } 
  • Thank you. The pieces of your code will be helpful. - zloctb

"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.

  • one
    @maxSLON yes no, everything is correct. The application should read json, if it is not json that comes - just interrupt execution. - etki