Search code examples
jq

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 :

"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"))