KNOWLEDGE BASE
Log In    |    Knowledge Base    |    4D Home
Tech Tip: How to check if TEXT is an OBJECT / JSON
PRODUCT: 4D | VERSION: 15.2 | PLATFORM: Mac & Win
Published On: June 23, 2016

Here is a utility method that can be used to check if some TEXT represents a valid OBJECT / JSON:

// UTIL_IS_TEXT_AN_OBJECT
// $1 := TEXT of JSON to check
// $0 := BOOLEAN representing validitity
If (Count parameters=1)
   C_BOOLEAN($0)
   C_TEXT($method;$result;$1)
   $method:=Method called on error
   ON ERR CALL("ErrHandler")
   $result:=JSON Stringify(JSON Parse($1;is object))
   ON ERR CALL($method)
   If (($result="") | ($result="undefined"))
      $0:=False
   Else
      $0:=True
   End if
End if


Create a method named ErrHandler to handle the error:
// on err call
// do nothing


If this method is saved as UTIL_IS_TEXT_AN_OBJECT it could be used like this:
C_TEXT($text)
$text:="{\"OK\": True}" // The JSON is invalid because True should be written as true.
If (UTIL_IS_TEXT_AN_OBJECT ($text))
   C_OBJECT($ob)
   $ob:=JSON Parse($text;Is object)
Else
   ALERT("$text is not an object")
End if


This is useful for checking arbitrary data before parsing it as an object because an error is generated if you attempt to parse invalid text as a object.


Updated: February 1st, 2018