Diego Bernardes
Diego Bernardes

Reputation: 179

Multiple operations with an array

I'm using an application that depends on a JSON config file and unfortunately, there is no way to configure it for different environments. The configuration file looks like this:

{
  "allowed_origin": [
    "http://localhost",
    "http://companydev.com",
    "http://company.com"
  "
}

For dev we would like to have this:

{
  "allowed_origin": [
    "http://localhost",
    "http://companydev.com"
  "
}

For prod:

{
  "allowed_origin": [
    "http://company.com"
  "
}

I don't know if it's possible to process the JSON in a single jq pass. To delete the localhost this works . allowed_origin |= map(select(index("http://localhost")|not)). But how to do the other one? I tried somethings but I did not have any success.

Upvotes: 1

Views: 34

Answers (1)

choroba
choroba

Reputation: 242123

Do you mean something like this?

I used del to remove an entry instead of |= with map.

#!/bin/bash
env=$1
json=$2

case "$env" in
    (dev)  indices='index("http://company.com")' ;;
    (prod) indices='index("http://company.com"),index("http://localhost")' ;;
    (*) echo Invalid env "$env" >&2 ;;
esac

command="del(.allowed_origin[.allowed_origin|$indices])"
echo "$command"
jq "$command" "$json"

Upvotes: 1

Related Questions