This is a very simple tool for validating a JSON string. It utilises jq for this purpose and wraps the output into something more consumable within other scripts.
Also see: json-lint for out travis plugin that performs a similar function.
There are 4 different options when it comes to using the validation tool.
- You can validate a raw json string
- You can validate the contents of a file
- You can just make use of error / return codes
- You can be given error messages as well as return codes
The first 2 options are handled by 2 different exposed functions.
source validate-json.sh
validate_json "<raw json string>"
source validate-json.sh
validate_json_from_file "<filename>"
This function will load the file contents into a string and then execute validate_json, so the final validation method is exactly the same to ensure identical results.
In additional to the two different wants to pass the data to the validator there are also 2 different ways to get data out of the validator.
Verbose mode will display messages relating to the validity of the string, either everything was ok, or the specific error message returned by jq. It will also use return codes for success (0) and failure (1).
source validate-json.sh
validate_json_from_file "<filename>"
This mode will suppress all output to the screen and will only use return codes.
silence_messages=true
source validate-json.sh
validate_json_from_file "<filename>"
This is particularly useful if you want to embed the validation into another script and take different actions depending on the result.
silence_messages=true
source validate-json.sh
if validate_json_from_file "<filename>"; then
go_perform_some_action_on_data
else
do_something_else_like_raise_an_error
fi