Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{
  "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.

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading