How to rename a nested JSON field?
How am I supposed to rename a nested json field? Suppose I have input like
[{"Body": {"meta": ... }}, {{"Body": {"meta": ... }}]
and I would rename "meta" to "renamed_meta"
What works is:
mlr -j rename Body,renamed_Body <file.json>
This renames Body to renamed_Body
but this failes:
mlr -j rename Body.meta,Body.renamed_meta <file.json>
How am I supposed to rename a nested json field?
Hi, you could use put and assign a new field.
Running
echo '[{ "Body": { "meta": 5 } }, { "Body": { "meta": 6 } } ] ' | mlr -j put '$Body.renamed_meta = $Body.meta; unset $Body.meta'
you get
[
{
"Body": {
"renamed_meta": 5
}
},
{
"Body": {
"renamed_meta": 6
}
}
]
Or you can first flatten, then rename and then unflatten it.
Running
echo '[{ "Body": { "meta": 5 } }, { "Body": { "meta": 6 } } ] ' | mlr -j flatten then rename Body.meta,Body.renamed_meta then unflatten
you get
[
{
"Body": {
"renamed_meta": 5
}
},
{
"Body": {
"renamed_meta": 6
}
}
]
Hi, you could use put and assign a new field.
Running
echo '[{ "Body": { "meta": 5 } }, { "Body": { "meta": 6 } } ] ' | mlr -j put '$Body.renamed_meta = $Body.meta; unset $Body.meta'
I went with this solution as it seems more flexible. Works fine. Unless someone want's to chime in and suggest that a rename should work in this siutation.
I suggest a documentation update as rename would be the natural fit for that, therefore not closing,
Thanks @the42 and @aborruso ! Definitely worth documenting. :)