Search code examples
jsonjmespath

How to return a child node and a parent node attribute in the same query JMES Path for JSON object


Considert we have this JSON:

{  
   "A":[  
      {  
         "AT":"text"
      },
      {  
         "AT":"text2"
      }
   ],
   "B":[  
      {  
         "name":"text",
         "power":10
      },
      {  
         "name":"text1",
         "power":20
      },
      {  
         "name":"text2",
         "power":40
      }
   ]
}

I want to return "AT" and the power corresponding to "AT", so I don't want to return "text1" but just [["text",10],["text2",40]]. This query [A[*].AT,B[*].power] return this: [["text","text2"],[10,20,40]]. So it's not exactly what I want because I don't want the extra value: 20 from "text1". How can I fix that ?

EDIT: I found this portion of code @.B[?contains(['text','text2'],name)].[name,power][][] it return ["text",10,"text2",40] this is the good result BUT the query isn't dynamics, because in the contain I have this ['text','text2'] and I want to replace this portion of code with a nested query if it's possible, so, how can I do that ?


Solution

  • I don't think it's possible because as I know we can't store variables in JMES Path ad we can't use the current-node(@) in array filter as @.B[?contains(@[].A[].AT,name)].[name,power][][] . Apparently JMES Path doesn't know to retrieve informations from node A once it get into the node B. You should use jq, with this query:

    ( .B | map({(.name): .power}) | add ) as $b | .A | map(.AT | [., $b[.]]) | add