Quick tip today. I wanted to validate my JSON file with jq. I think the common usage is to pipe text into jq but this is slow. jq has the ability to read the file directly, which is great if your json file is large. Next, we need to tell jq print out the loaded file. 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 not 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!"
}