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

Add a new element to a JSON array using jq

I have a json as mentioned in the first section and i want to add an element("image": "<IMAGE1_NAME>",) in the json as specified in the expected output.

I tired to use jq like this:

'.containerDefinitions += {"operation":"delete"}'

but this seem to not work. can anyone help me the jq command to achieve the result i want.

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

{
"taskDefinitionArn": "arn:aws",
"containerDefinitions": [
    {
        "name": "dev-service",
        "cpu": 0,
        "portMappings": [
            {
                "containerPort": 8080,
                "hostPort": 8080,
                "protocol": "tcp"
            }
        ],
        "essential": true,
        "environment": [
            {
                "name": "message",
                "value": "Hi, EMC!!"
            }
        ]
        }
    }
]

}

expected output :

{
"taskDefinitionArn": "arn:aws:ecs:us-west-2:619867110810:task-definition/emc-dev-backend:30",
"containerDefinitions": [
    {
        "name": "dev-service",
        "image": "<IMAGE1_NAME>",
        "cpu": 0,
        "portMappings": [
            {
                "containerPort": 8080,
                "hostPort": 8080,
                "protocol": "tcp"
            }
        ],
        "essential": true,
        "environment": [
            {
                "name": "message",
                "value": "Hi, EMC!!"
            }
        ]
        }
    }
]

}

>Solution :

Since it’s an array, we’ll need some sort of loop, use

.containerDefinitions[] += { "image":"IMAGE1_NAME" }

To add { "image":"IMAGE1_NAME" } on each item in the containerDefinitions key


JqPlay Demo

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