Jq: Rename a key in an object

Created on 21 Jun 2016  路  2Comments  路  Source: stedolan/jq

How is it possible to rename a key ?

Say I have :

'{"long_message" : "Foo bar baz"}'

and I'd like to have

'{"msg" : "Foo bar baz"}'

Is this achievable with jq ?

Most helpful comment

Suppose you have an arbitrary object, obj, which is known to contain a key, "from", and is also known not to contain the key "to". To rename "from" to "to", you could use the filter:

. + {"to": .from} | del(.from)

This could of course be abstracted into a new jq filter.

To rename a key programmatically, you could use with_entries, e.g.

with_entries( if .key | contains("-") then .key |= sub("-";".") else . end)

See also the Q: How can I rename the keys of an object in the jq FAQ

All 2 comments

Suppose you have an arbitrary object, obj, which is known to contain a key, "from", and is also known not to contain the key "to". To rename "from" to "to", you could use the filter:

. + {"to": .from} | del(.from)

This could of course be abstracted into a new jq filter.

To rename a key programmatically, you could use with_entries, e.g.

with_entries( if .key | contains("-") then .key |= sub("-";".") else . end)

See also the Q: How can I rename the keys of an object in the jq FAQ

Thanks !

Was this page helpful?
0 / 5 - 0 ratings

Related issues

neowulf picture neowulf  路  3Comments

ghost picture ghost  路  4Comments

lhunath picture lhunath  路  3Comments

rclod picture rclod  路  4Comments

thelonious picture thelonious  路  4Comments