How to check if a string is a valid JSON string in JavaScript without using Try/Catch

前端 未结 24 1783
暖寄归人
暖寄归人 2020-11-22 07:50

Something like:

var jsonString = \'{ \"Id\": 1, \"Name\": \"Coke\" }\';

//should be true
IsJsonString(jsonString);

//should be false
IsJsonString(\"foo\");         


        
相关标签:
24条回答
  • 2020-11-22 08:36

    This answer to reduce the cost of trycatch statement.

    I used JQuery to parse JSON strings and I used trycatch statement to handle exceptions, but throwing exceptions for un-parsable strings slowed down my code, so I used simple Regex to check the string if it is a possible JSON string or not without going feather by checking it's syntax, then I used the regular way by parsing the string using JQuery :

    if (typeof jsonData == 'string') {
        if (! /^[\[|\{](\s|.*|\w)*[\]|\}]$/.test(jsonData)) {
            return jsonData;
        }
    }
    
    try {
        jsonData = $.parseJSON(jsonData);
    } catch (e) {
    
    }
    

    I wrapped the previous code in a recursive function to parse nested JSON responses.

    0 讨论(0)
  • 2020-11-22 08:38

    Very Simple one-liner code ( But Hacky approach )

    if (expected_json.id === undefined){
       // not a json
    }
    else{
       // json
    }
    

    NOTE: This only works if you are expecting something is JSON string like id. I am using it for an API and expecting the result either in JSON or some error string.

    0 讨论(0)
  • 2020-11-22 08:39

    I thought I'd add my approach, in the context of a practical example. I use a similar check when dealing with values going in and coming out of Memjs, so even though the value saved may be string, array or object, Memjs expects a string. The function first checks if a key/value pair already exists, if it does then a precheck is done to determine if value needs to be parsed before being returned:

      function checkMem(memStr) {
        let first = memStr.slice(0, 1)
        if (first === '[' || first === '{') return JSON.parse(memStr)
        else return memStr
      }
    

    Otherwise, the callback function is invoked to create the value, then a check is done on the result to see if the value needs to be stringified before going into Memjs, then the result from the callback is returned.

      async function getVal() {
        let result = await o.cb(o.params)
        setMem(result)
        return result
    
        function setMem(result) {
          if (typeof result !== 'string') {
            let value = JSON.stringify(result)
            setValue(key, value)
          }
          else setValue(key, result)
        }
      }
    

    The complete code is below. Of course this approach assumes that the arrays/objects going in and coming out are properly formatted (i.e. something like "{ key: 'testkey']" would never happen, because all the proper validations are done before the key/value pairs ever reach this function). And also that you are only inputting strings into memjs and not integers or other non object/arrays-types.

    async function getMem(o) {
      let resp
      let key = JSON.stringify(o.key)
      let memStr = await getValue(key)
      if (!memStr) resp = await getVal()
      else resp = checkMem(memStr)
      return resp
    
      function checkMem(memStr) {
        let first = memStr.slice(0, 1)
        if (first === '[' || first === '{') return JSON.parse(memStr)
        else return memStr
      }
    
      async function getVal() {
        let result = await o.cb(o.params)
        setMem(result)
        return result
    
        function setMem(result) {
          if (typeof result !== 'string') {
            let value = JSON.stringify(result)
            setValue(key, value)
          }
          else setValue(key, result)
        }
      }
    }
    
    0 讨论(0)
  • 2020-11-22 08:40

    var jsonstring='[{"ConnectionString":"aaaaaa","Server":"ssssss"}]';
    
    if(((x)=>{try{JSON.parse(x);return true;}catch(e){return false}})(jsonstring)){
    
    document.write("valide json")
    
    }else{
    document.write("invalide json")
    }

    0 讨论(0)
  • 2020-11-22 08:41

    A comment first. The question was about not using try/catch.
    If you do not mind to use it, read the answer below. Here we just check a JSON string using a regexp, and it will work in most cases, not all cases.

    Have a look around the line 450 in https://github.com/douglascrockford/JSON-js/blob/master/json2.js

    There is a regexp that check for a valid JSON, something like:

    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
    
    }
    

    EDIT: The new version of json2.js makes a more advanced parsing than above, but still based on a regexp replace ( from the comment of @Mrchief )

    0 讨论(0)
  • 2020-11-22 08:42

    Maybe it will useful:

        function parseJson(code)
    {
        try {
            return JSON.parse(code);
        } catch (e) {
            return code;
        }
    }
    function parseJsonJQ(code)
    {
        try {
            return $.parseJSON(code);
        } catch (e) {
            return code;
        }
    }
    
    var str =  "{\"a\":1,\"b\":2,\"c\":3,\"d\":4,\"e\":5}";
    alert(typeof parseJson(str));
    alert(typeof parseJsonJQ(str));
    var str_b  = "c";
    alert(typeof parseJson(str_b));
    alert(typeof parseJsonJQ(str_b));
    

    output:

    IE7: string,object,string,string

    CHROME: object,object,string,string

    0 讨论(0)
提交回复
热议问题