Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rename property of an object inside array

Tags:

This is my input JSON

{
"uuid":123,
"description": [
    {
        "car_name":"Toyota",
        "saleDate":"23 May 2017"
    }
  ]
}

Expected output:

{
"uuid":123,
"description": [
    {
        "name":"Toyota",
        "saleDate":"23 May 2017"
    }
  ]
}

Rule : .description[]|={name:.car_name,saleDate}

I am able to achieve the desired result with this rule. However, is there a way I can rename the 'car_name' property to 'name' and also not mention all the other properties ( in this case, 'saleDate') in the rule. I might end up having 50+ properties inside the object and I do not want to mention all of them in the rule.

There can be more than one object in the array.

like image 430
Devadas Bhat Avatar asked Jun 05 '17 11:06

Devadas Bhat


People also ask

How do you change an object property in an array?

To update an object's property in an array of objects, use the map() method to iterate over the array. On each iteration, check if the current object is the one to be updated. If it is, modify the object and return the result, otherwise return the object as is. Copied!

Can a property of an object be an array?

Just as object properties can store values of any primitive data type (as well as an array or another object), so too can arrays consist of strings, numbers, booleans, objects, or even other arrays.

How do I remove a property from an array of objects?

To remove a property from all objects in an array:Use the Array. forEach() method to iterate over the array. On each iteration, use the delete operator to delete the specific property. The property will get removed from all objects in the array.


1 Answers

To preserve the order of keys while being sure only to change the specific key name:

jq '.description[] |= with_entries(if .key == "car_name" then .key = "name" else . end)'
like image 122
peak Avatar answered Sep 21 '22 20:09

peak