简体   繁体   中英

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?

You don't need with_entries .

map_values(.value)

Online demo

with_entries helps:

with_entries(.value |= .value)

which is short for to_entries | map(.value |=.value) | from_entries 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 )

Your attempt

.[] | {value}

just misses the update assignment.

This will work as expected:

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

Demo

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM