Home > OS >  Insert value into JSON array if it is not already present
Insert value into JSON array if it is not already present

Time:10-26

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.

CodePudding user response:

You don't need a loop for that

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

CodePudding user response:

Here's another way using the alternative operator // to default to the array's length for the item's index:

jq --arg order 'lasagna' '
  (.foods.menu | .[index($order) // length]) = $order
' response.json
  • Related