KNOWLEDGE BASE
Log In    |    Knowledge Base    |    4D Home
Tech Tip: Checking JSON to Parse
PRODUCT: 4D | VERSION: 16R4 | PLATFORM: Mac & Win
Published On: February 15, 2018

As of 4D v16R4 the JSON Parse command can now handle a new type of json string, a collection. Prior to v16R4, a json string with a collection would have to be parsed out with JSON PARSE ARRAY, returning a variable of type ARRAY OBJECT.

BEFORE v16R4:


AFTER v16R4:


Handling a json string after parsing it out requires knowing what type of variable is returned from the JSON Parse function, and so it is important to ensure the variable that you are parsing your json string into is of the correct type. Thankfully you are using 4D, and checking the type of variable returned from the JSON Parse command is easy!

The 4D command Value type, used in conjunction with JSON Parse, will determine the type of variable comes from parsing the json string.

C_LONGINT($type_l)
$type_l:=Value type(JSON Parse($json_string))

For example, the above code would return 38 if the parsed string is an object, 2 for a text variable, 42 for a collection, 9 for a number, 4 for a date, and 6 for a boolean. For a full list of variable types returned by the Value type command, see the documentation.

Example json string containing a collection:

[{"name":"Kristopher","company":"4D Inc"},true,"San Jose"]

This example collection above contains 3 elements which are an object, a boolean, and a text string. To view this another way, the "pretty" version of this collection looks like this:

[
  {
    name: "Kristopher",
    company: "4D Inc"
  },
  true,
  "San Jose"
]

Using the JSON Parse command on this example json string would return a collection, as seen above, and so accessing the items within that collection (with object notation) would look like this if accessing, for example, the "name" attribute from the object:

C_TEXT($json_string;$name_t)
C_COLLECTION($output_col)
$json_string:="[{\"name\":\"Kristopher\",\"company\":\"4D Inc\"},true,\"San Jose\"]"
$output_col:=New Collection
$output_col:=JSON Parse($json_string)
$name_t:=$output_col[0].name

If the json string were different, for example:

{"name":"Kristopher","company":"4D Inc","location":"San Jose","employed";true}

{
  name: "Kristopher",
  company: "4D Inc",
  location: "San Jose",
  employed: true
}

Then parsing the string and accessing the name would be done differently:

C_TEXT($json_string;$name_t)
C_OBJECT($output_obj)
$json_string:="{\"name\":\"Kristopher\",\"company\":\"4D Inc\",\"location\":\"San Jose\",\"employed\";true}"
$output_obj:=New Object
$output_obj:=JSON Parse($json_string)
$name_t:=$output_obj.name