miller icon indicating copy to clipboard operation
miller copied to clipboard

How to rename a nested JSON field?

Open the42 opened this issue 6 months ago • 4 comments

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?

the42 avatar Jun 12 '25 14:06 the42

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
    }
  }
]

aborruso avatar Jun 12 '25 15:06 aborruso

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
    }
  }
]

aborruso avatar Jun 12 '25 15:06 aborruso

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,

the42 avatar Jun 16 '25 05:06 the42

Thanks @the42 and @aborruso ! Definitely worth documenting. :)

johnkerl avatar Jun 16 '25 15:06 johnkerl