Enigmatic
Enigmatic

Reputation: 4138

jq: Map from nested JSON

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?

Upvotes: 2

Views: 1662

Answers (4)

axiac
axiac

Reputation: 72177

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.

Upvotes: 1

pmf
pmf

Reputation: 36033

Your attempt

.[] | {value}

just misses the update assignment.

This will work as expected:

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

Demo

Upvotes: 2

oguz ismail
oguz ismail

Reputation: 50750

You don't need with_entries.

map_values(.value)

Online demo

Upvotes: 5

knittl
knittl

Reputation: 265151

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)

Upvotes: 2

Related Questions