How can jq be used to insert dynamic field names recursively for all objects in an array? How can jq be used to insert dynamic field names recursively for all objects in an array? json json

How can jq be used to insert dynamic field names recursively for all objects in an array?


The key to a simple solution is |=. Here's one using map:

.records |= map( .Account.Id as $x                  | del(.Account)                 | . + {AccountID: $x} )

which can be simplified to:

.records |= map( . + {AccountID: .Account.Id}                 | del(.Account) )

Either of these can easily be adapted to the case where the two field names are passed in as arguments, or if they must be inferred from the "owner" of "Id".


Adapting peak's answer to use the dynamic field name:

jq -c --arg field "Account" \      --arg field_name_id "AccountID" '.records |= map(.[$field].Id as $x                  | del(.[$field])                  | . + {($field_name_id): $x})'