Home > other >  jq: Map from nested JSON
jq: Map from nested JSON

Time:09-20

I have the following JSON:

{
  "A": {
    "type": "string",
    "value": "value_A"
  },
  "B": {
    "type": "string",
    "value": "value_B"
  }
}

...and am trying to use JQ to result in the following:

Desired Output

{
  "A": "value_A",
  "B": "value_B"
}

...where the key takes the direct value of node.value.


My current attempt:

.[] | {value}

...returns the following:

{
  "value": "value_A"
}
{
  "value": "value_B"
}

How can I use JQ to produce the desired JSON?

CodePudding user response:

You don't need with_entries.

map_values(.value)

Online demo

CodePudding user response:

with_entries helps:

with_entries(.value |= .value)

which is short for to_entries | map(.value |= .value) | from_entries

to_entries transforms an object of form {a:b} into an array in the form [{key:a, value:b}], so in your example:

{
  "key": "A",
  "value": {
    "type": "string",
    "value": "value_A"
  }
}

.value |= .value then assigns the content of .value.value to .value, leaving you with:

{
  "key": "A",
  "value": "value_A"
}

which is then converted to an object again by from_entries (repeated from above: with_entries(f) is equivalent to from_entries|map(f)|from_entries)

CodePudding user response:

Your attempt

.[] | {value}

just misses the update assignment.

This will work as expected:

.[] |= .value
{
  "A": "value_A",
  "B": "value_B"
}

Demo

CodePudding user response:

Use the function map_values():

map_values(.value)

It runs the filter passed as argument to each value of the input object, collects the results and associates them with the keys of the input object and returns an object.

Check it online.

  • Related