Tedd Tedd - 5 months ago 12
Bash Question

Adding One more Parent Attrubute To JSON through Command line

I want edit the structure of json through Terminal using terminal commands or scripts.
If I have a json file Structure like this:

{
"Helloo": [
{

"AlbumTitle": {
"S": "Famous"
},
"SongTitle": {
"S": "Call Me Today"
},
"Artist": {
"S": "No One You Know"
}

},
{

"AlbumTitle": {
"S": "Famous1"
},
"SongTitle": {
"S": "Call Me Today1"
},
"Artist": {
"S": "No One You Know11"
}

}
],
"Music": [
{

"Album": {
"S": "Pop Songs"
},
"Production": {
"S": "X-series"
},
"Song": {
"S": "Once upon
},
"Artist": {
"S": "XYZ"
}

}
]
}


So here i want add "Putrequest" and "Item" attributes to each item of the array.. So i want the output like this:

{
"Helloo": [
{
PutRequest":{
"Item":{

"AlbumTitle": {
"S": "Famous"
},
"SongTitle": {
"S": "Call Me Today"
},
"Artist": {
"S": "No One You Know"
}

}
}
},
{
PutRequest":{
"Item":{

"AlbumTitle": {
"S": "Famous1"
},
"SongTitle": {
"S": "Call Me Today1"
},
"Artist": {
"S": "No One You Know11"
}

}
}
}
],
"Music": [
{
PutRequest":{
"Item":{
"Album": {
"S": "Pop Songs"
},
"Production": {
"S": "X-series"
},
"Song": {
"S": "Once upon
},
"Artist": {
"S": "XYZ"
}
}
}
}
]
}


I tried to use Jq for this but still struggling.. Please help me To add these attributes to json using command prompt or bash/shell scripting.
Thanks

Answer

Assuming you actually got valid JSON the following jq expression might work for you:

map_values(map({"PutRequest": { "Item": .}}))

Usage:

jq 'map_values(map({"PutRequest": { "Item": .}}))' file.json

Breakdown:

map_values(           # Map values iterate over an object and assign the 
                      # returned value to the property
  map(                # Map iterate over an array and assign the returned value
                      # to the index, and creates a new array if an object is
                      # mapped
    {                 # Return an object
      "PutRequest": { # With PutRequest as a property
        "Item": .     # And Item, which contains the value (.)
      }
    }
  )
)