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

前端 未结 24 2219
暖寄归人
暖寄归人 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: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)
        }
      }
    }
    

提交回复
热议问题