Check if string is valid JSON with jq

I need to catch a mistake when lifting a service. The answer may be null , a string error message like

error services-migration/foobar: Not found: services-migration/foobar

or valid JSON when everything is ok. I was wondering if there is a jq way to just check if the provided string is valid JSON. I could check the string for some keywords, such as error fe, but I am looking for a more reliable option, for example, for example. I get true/false or 1/0 from jq. I was looking through jq as well as some questions here about SO, but it was all about finding and displaying key values ​​from JSON, but nothing related to just checking the string.

UPDATE:

I have it:

  result=$(some command) 

from which the result is the string error services-migration/foobar: Not found: services-migration/foobar

And then the if statement:

  if jq -e . >/dev/null 2>&1 <<<"$result"; then echo "it catches it" else echo "it doesn't catch it" fi 

And it always ends in else .

+5
source share
2 answers

From the manual:

-e / - exit-status:

Sets the output status jq to 0 if the last output value was neither false or zero, 1 if the last output value was either false or zero, or 4 if no valid result was obtained. Typically, jq exits with 2 if there was a usage problem or a system error, 3 if there was a compilation error for the jq program, or 0 if the jq program was running.

So you can use:

 if jq -e . >/dev/null 2>&1 <<<"$json_string"; then echo "Parsed JSON successfully and got something other than false/null" else echo "Failed to parse JSON, or got false/null" fi 

In fact, if you do not need to distinguish between different types of errors, you can simply lose the -e switch. In this case, everything that is considered valid, JSON (including false / null) will be successfully parsed by the filter . , and the program will succeed, so the if branch will execute.

+6
source

It works for me

 echo $json_string | ./jq -e . >/dev/null 2>&1 | echo ${PIPESTATUS[1]} 

which returns a return code:

  • 0 - Success
  • 1 - Failed
  • 4 - Invalid

You can then evaluate the return code with an additional code.

+2
source

Source: https://habr.com/ru/post/1272915/


All Articles