'jq error when using if then else with scan

I have json:

{
  "apiVersion": "projectcalico.org/v3",
  "kind": "NetworkPolicy",
  "metadata": {
    "name": "allow-tcp-6379",
    "namespace": "production"
  },
  "spec": {
    "selector": "all()",
...
}

I select the fields I need with the command jq 'if .spec.selector == "all()" then "{}" else (scan("([0-9A-Za-z_]+) == '([0-9A-Za-z_]+)") | {(.[0]): .[1]}) end | {selector: .}'

But if I change the field to .spec.selector: "app =='nginx'" then I get an error - jq: error (at <stdin>:39): object ({"apiVersio...) cannot be matched, as it is not a string exit status 5

How to fix this?

jqplay: https://jqplay.org/s/7zS1CTHM69

jq


Solution 1:[1]

You're applying scan to the wrong thing.

if .spec.selector == "all()" then
   "{}"
else
   .spec.selector | 
   scan("([0-9A-Za-z_]+) == '([0-9A-Za-z_]+)") |
   { (.[0]): .[1] }
end

This simplifies to

.spec.selector |
if . == "all()" then
   "{}"
else
   scan("([0-9A-Za-z_]+) == '([0-9A-Za-z_]+)") |
   { (.[0]): .[1] }
end

It seems weird that you output a string in one path and an object in the other. Is this correct?

In addition to not specifying what you want from the three alternatives (all(), x == 'y', other), you did not specify what output from the overall program, so it's not clear how this should be incorporated into your program.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1