Prototype: validdata(data_container, type, strict)

Return type: boolean

Description: Validates a JSON container from data_container and returns "true" if the contents are valid JSON. An optional second argument strict may be used to enable strict validation. When set to "true" the function will not evaluate to true for JSON primitives. The default value of strictis "false".

The strict behavior matches the expectations in other parts of policy language. Notably, data containers and functions like readjson() and parsejson() expect JSON containers (arrays and objects) not primitives. Thus, using validdata() with strict set to "true" is an effective way to check if something can be parsed by those functions.

This function is intended to be expanded with functionality for validating CSV and YAML files eventually, mirroring readdata(). If type is JSON, it behaves the same as validjson().

Arguments:

  • data_container: string - String to validate as JSON - in the range: .*
  • type: - Type of data to validate - one of
    • JSON
  • strict: - Enable more strict validation, requiring the result to be a valid data container, matching the requirements of parsejson(). - one of
    • true
    • false
    • yes
    • no
    • on
    • off

Example:

Run:

code
bundle agent main
{
  vars:
    "json_string" string => '{"test": [1, 2, 3]}';
    "primitive" string => "\"hello\"";

  reports:
    "This JSON string is valid!"
      if => validdata("$(json_string)", "JSON");
    "This JSON string is not valid."
      unless => validdata("$(json_string)", "JSON");

    "This JSON string is valid! (strict)"
      if => validdata("$(primitive)", "JSON", "true");
    "This JSON string is not valid. (strict)"
      unless => validdata("$(primitive)", "JSON", "true");
}

Output:

code
R: This JSON string is valid!
R: This JSON string is not valid. (strict)

See also: readdata(), validjson()

History: Was introduced in 3.16.0.