Sunday, October 30, 2022

[SOLVED] Insert value into JSON array if it is not already present

Issue

I'm building a bash script that will read the response from an API and insert a value within a [] list (not {} array) if the value isn't present. Fake example response from API:

#response.json contains:

{
    "foods": {
        "menu": [
            "tacos",
            "spaghetti",
            "pizza",
            "chicken_florentine",
            "bacon_cheeseburge",
            "chow_mein",
            "sushi",
            "chocolate",
            "whiskey"
        ]
    }
}

The variable from my bash script is order="lasagna". If 'foods.menu[]' contains $order then do nothing, else insert $order value into 'foods.menu[]'.

Using bash variable order="lasagna" which currently doesn't exist in 'foods.menu[]', the resulting json should be:

{
    "foods": {
        "menu": [
            "tacos",
            "spaghetti",
            "pizza",
            "chicken_florentine",
            "bacon_cheeseburge",
            "chow_mein",
            "sushi",
            "chocolate",
            "whiskey",
            "lasagna" <----
        ]
    }
}

I started with trying a bash for loop and variations of jq's if-then-else, select, and contains but went down a rabbit hole. Any help is appreciated.


Solution

You don't need a loop for that

jq --arg order lasagna '.foods.menu |= if index($order) then . else . + [$order] end' response.json

But you may need one for inserting multiple orders

jq 'reduce $ARGS.positional[] as $order (.;
  .foods.menu |= if index($order) then . else . + [$order] end
)' response.json --args apple banana sushi


Answered By - oguz ismail
Answer Checked By - Mary Flores (WPSolving Volunteer)