Search code examples
jsonschemajq

How can i validate a json against a template in jq?


I am having a shell script . in my shell script i have a command that returns the following data as a json .

{
  "remoteIds": [
    {
      "remoteId": "[fd00:10:244:1:0:0:0:12]--(http://fd00-10-244-1--12.nspace.pod:8080)",
      "requestsReceived": 1
    }
}

i want to validate the above output with a json template. in my json template i can provide the port, nspace , protocol (http) & requestsReceived . How can i design a json template and validate against the json data . i can use jq and bash script

The following will be a template in my mind

{
  "remoteIds": [
    {
      "remoteId": "[*]--(http://*.nspace.pod:8080)",
      "requestsReceived": 1
    }
}

thank you


Solution

  • If you don't want to tangle with a full-fledged generic schema definition ecosystem and don't mind "rolling your own" validation engine, you might wish to consider the following illustration:

    < input.json jq --slurpfile template template.json '
      def validate($template):
        ($template | .remoteIds[0] | keys) as $keys
        | (type == "object") and
          (.remoteIds | type) == "array" and
          all(.remoteIds[]; keys == $keys) and
          all(.remoteIds[].remoteId; 
              test("^\\[.*\\]--[(]http://.*[.]nspace[.]pod:8080[)]$") )
      ;
    
    validate($template[0])
    '
    

    This incidentally works with all three of the major jq implementations: the standard C-based implementation; gojq; and jaq.