bisgardo
bisgardo

Reputation: 4600

jq: Include the lookup key as a field in the result value

I have a JSON object of the following form:

{
  "vars": {
    "node1": {"field1": "a", "field2": "b"},
    "node2": {"field1": "x", "field2": "y"}
    "unrelated": {"blah": "blah"}
  },
  "nodes": ["node1", "node2"]
}

Now, I can get the fields per node (excluding unrelated) using the following jq expression:

.vars[.nodes[]]

Output:

{
  "field1": "a",
  "field2": "b"
}
{
  "field1": "x",
  "field2": "y"
}

My question is, how do I include the vars key as a field in the output, i.e.

{
  "node": "node1",
  "field1": "a",
  "field2": "b"
}
{
  "node": "node2",
  "field1": "x",
  "field2": "y"
}

The name of the key (node in the example) is not important.

Based on this post I found an approximate solution:

.vars | to_entries | map_values(.value + {node: .key})[]

which outputs

{
  "field1": "a",
  "field2": "b",
  "node": "node1"
}
{
  "field1": "x",
  "field2": "y",
  "node": "node2"
}
{
  "blah": "blah",
  "node": "unrelated"
}

But it still includes the unrelated field which is shouldn't.

Upvotes: 2

Views: 187

Answers (1)

pmf
pmf

Reputation: 36086

Store the nodes array's elements in a variable for reference. Storing the elements rather than the whole array automatically also iterates for the next step. Then, just compose your desired output objects using the nodes array item as object {$node} added to the looked-up object in .vars[$node].

jq '.nodes[] as $node | {$node} + .vars[$node]'
{
  "node": "node1",
  "field1": "a",
  "field2": "b"
}
{
  "node": "node2",
  "field1": "x",
  "field2": "y"
}

Demo

Upvotes: 3

Related Questions