Quick tip today. I wanted to validate my JSON file with jq. jq can read files directly rather than requiring piped input, which is useful for large files. jq has the ability to read the file directly, which is great if your json file is large. By default jq prints out the loaded file. However, we use empty to not display any output. By default if there are any errors in the json file jq will output where the error is.

So in summary, we disabled printing the json file and we will get any errors if found. If there are no errors, there will be no output.

jq empty file.json

Save the Error into a variable in PowerShell

$resultError = $( & jq empty .\file.json ) 2>&1

$resultError will now contain the error. For example:

> $resultError
jq: parse error: Unfinished JSON term at EOF at line 2126, column 0

If there is no error, $resultError will be empty.

Save the Error into a variable and check the variable

Let’s say we want to handle the error, as a one liner:

$resultError = $( & jq empty .\trace.json ) 2>&1 ; if ( $resultError ) { Write "Error!: $resultError" } else { Write "Successful!" }

or written more clearly:

$resultError = $( & jq empty .\trace.json ) 2>&1

if ( $resultError )
{
    # Handle error
    Write "Error!: $resultError"
}
else
{
    Write "Successful!"
}