Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

jq rename nested json key and place under same key

I want to rename nested json key and keep under same schema.

Input:

"properties":
 {
  "name": "Ram",
  "age": "17",
  "department": "Sony"
 }

Code : jq '[.["properties.company"] = .properties.department| del(.properties.department)]'  file

Output:

"properties":
 {
  "name": "Ram",
  "age": "17"  
 }
"properties.company" = "Sony"

Expected Output should be :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

"properties":
 {
  "name": "Ram",
  "age": "17",
  "company": "Sony"  
 }

What I am doing wrong ?

>Solution :

You have several options, but for that you need to have a valid input JSON such as:

{
  "properties": {
    "name": "Ram",
    "age": "17",
    "department": "Sony"
  }
}

With del

This assigns the new property first, then deletes the old one.

.properties | .company = .department | del(.department)

Constructing a new object with {}

This is building a new object from scratch, copying all existing properties and renaming as needed.

.properties |= { name, age, company: .department }

Merging objects

This is a combination of the first two approaches. The property is deleted, while it is being renamed in the new object. Both objects are ultimately merged to form the result.

.properties |=  del(.department) + { company: .department }

Changing key name with with_entries

This iterates over all key-value pairs and (re-)assigns the key name.

.properties |= with_entries(.key |= if . == "department" then "company" else . end)

or if you dislike ifs: same as above, but uses select(cond) // alternative to select an alternative value unless the condition is met.

.properties |= with_entries(.key |= (select(. != "department") // "company"))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading