It is necessary to get all key value pairs from JSON containing a specific '/' character

I have a specific json content for which I need to get all the keys that contain the / character in their values.

Json

{ "dig":  "sha256:d2aae00e4bc6424d8a6ae7639d41cfff8c5aa56fc6f573e64552a62f35b6293e",
 "name": "example",
 "binding": { 
   "wf.example.input1": "/path/to/file1",
   "wf.example.input2": "hello",
   "wf.example.input3":
     ["/path/to/file3",
      "/path/to/file4"],
   "wf.example.input4": 44
  }
}

      

I know I can get all keys containing a file path or an array of file paths using a query jq 'paths(type == "string" and contains("/"))'

. This will give me an output like:

[ "binding", "wf.example.input1" ]
[ "binding", "wf.example.input3", 0]
[ "binding", "wf.example.input3", 1 ]

      

Now that I have all the elements that contain some file paths as their values, is there a way to get both key and value for the same and then store them as different JSON? For example, in the JSON mentioned for this question, I need to get the output as another JSON containing all the paths agreed upon. My JSON output should look something like this.

 { "binding":
   { "wf.example.input1": "/path/to/file1",
     "wf.example.input3": [ "/path/to/file3", "/path/to/file4" ] 
   }
 }

      

+3


source to share


1 answer


The following jq filter will produce the desired result if the given input is very similar to the example, but it is far from reliable and ignores some details that are not clear from the description of the problem. However, it should be easy enough to modify the filter according to more precise specifications:

. as $in
| reduce paths(type == "string" and test("/")) as $path ({};
    ($in|getpath($path)) as $x
    | if ($path[-1]|type) == "string"
      then .[$path[-1]] = $x
      else .[$path[-2]|tostring] += [$x]
      end )
| {binding: .}

      



Output:

{
  "binding": {
    "wf.example.input1": "/path/to/file1",
    "wf.example.input3": [
      "/path/to/file3",
      "/path/to/file4"
    ]
  }
}

      

+2


source







All Articles