Skip to content

Instantly share code, notes, and snippets.

@kanwren
Last active May 14, 2025 20:33
Show Gist options
  • Select an option

  • Save kanwren/08455a1362939fb28507d12771998274 to your computer and use it in GitHub Desktop.

Select an option

Save kanwren/08455a1362939fb28507d12771998274 to your computer and use it in GitHub Desktop.
Parse a Kubernetes-style selector into a consumable tree in jq
def o(P):P//.;
def k(P):o(P|k(P));
def w(P;f):(.r=[]|P) as $r|.s=$r.s|.r+=[$r.r|f];
def s($r):(.s|match("^(?:"+$r+")")) as $m|.s|=.[$m.length:]|.m=$m.string;
def _:s(" *");
def r($r;f):s($r)|.r+=[.m|f];
def l($s):select(.s|startswith($s))|.s|=.[$s|length:]|_;
"[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?" as $d|
"(?:[a-zA-Z0-9](?:[a-zA-Z0-9_.-]{0,61}[a-zA-Z0-9])?)" as $l|
def K:r("(?:\($d)(?:\\.\($d))*/)?"+$l;.)|_;
def V:r($l+"?";.)|_;
def X:(w(l("!")|K;{key:.[0],op:"DoesNotExist"})//w(K|o((r("==?|!=";{"==":"In","=":"In","!=":"NotIn"}[.])|_|w(V;.))//((r("notin";"NotIn")//r("in";"In"))|_|l("(")|w(o(select(isempty(l(")")))|V|k(l(",")|V));.)|l(")")));if length==3 then {key:.[0],op:.[1],value:.[2]} else {key:.[0],op:"Exists"} end))|_;
{s:.,r:[]}|_|o(X|k(l(",")|X))|_|select(.s=="")|.r
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment