validjson
Prototype: validjson(string, strict)
Return type: boolean
Description: Validates a JSON container from string
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 strict
is "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 validjson()
with strict
set to "true"
is an effective way to check if something can be parsed by those functions.
Arguments:
string
:string
- String to validate as JSON - in the range:.*
strict
: - Enable more strict validation, requiring the result to be a valid data container, matching the requirements of parsejson(). - one oftrue
false
yes
no
on
off
Example:
Run:
bundle agent main
{
vars:
"json_string" string => '{"test": [1, 2, 3]}';
"primitive" string => "\"hello\"";
reports:
"This JSON string is valid!"
if => validjson("$(json_string)");
"This JSON string is not valid."
unless => validjson("$(json_string)");
"This JSON string is valid! (strict)"
if => validjson("$(primitive)", "true");
"This JSON string is not valid. (strict)"
unless => validjson("$(primitive)", "true");
}
Output:
R: This JSON string is valid!
R: This JSON string is not valid. (strict)
See also: readjson()
, validdata()
History: Was introduced in 3.16.0.