jq reduce (or map?) to transform to object containing {"key1":"value1","key2":"value2" }

Viewed 276

I have a json file in the following format:

{
    "foo": {
        "type": "string",
        "value": "hello"
    },
    "bar": {
        "type": "string",
        "value": "goodbye"
    }
}

I want to transform it to:

{
"foo": "hello",
"bar": "goodbye"
}

Best I have got to:

cat file.json | jq 'to_entries[] | reduce . as $item ({}; reduce . as $value ({}; $item.key + ":" + $item.value.value))'

which gives:

"foo:hello"
"bar:goodbye"

close, but still a long way to go.

All assistance appreciated. Thanks.

1 Answers

Using to_entries makes the problem much more difficult than it needs to be.

The problem can instead be solved in just one simple operation.

Since you want to update the value of each key, it makes sense to use map_values, which is meant for this purpose:

jq 'map_values(.value)' file.json

Output:

{
  "foo": "hello",
  "bar": "goodbye"
}

See the documentation for map_values here.

Related