0

I have below json file and according to product, i would like to get value of URL using bash.

I can write code using if else loop but that is not effective because whenever file gets changed, i have to update code. Is there any easy way to get the values dynamically using bash? For e.g. ${PRODUCT}.${URL} value.

Code:

if [ "${PRODUCT}" = "PRODUCT1" ]; then
   URL="https://product1.url:6080"
elif [ "${PRODUCT}" = "PRODUCT2" ]; then
   URL="https://testing.url.test:8090"
elif [ "${PRODUCT}" = "PRODUCT3" ]; then
   URL="https://start.url:18080"
fi

File content:

{
    "DEVICE"     : "DESKTOP",
    "ACCOUNT"    : "test123",

    "PRODUCT1": {
        "URL"    : "https://product1.url:6080"
    },

    "PRODUCT2": {
        "URL"    : "https://testing.url.test:8090"
    },

    "PRODUCT3": {
        "URL"    : "https://start.url:18080"
    }
}
Jitesh Sojitra
  • 3,655
  • 7
  • 27
  • 46
  • Use jq: https://stedolan.github.io/jq/ –  Jul 20 '19 at 18:24
  • You mean you want the last url whenever you execute a command? or do you mean whenever an entry is added to a file you want that url to get redirected somewhere? – Mihir Luthra Jul 20 '19 at 18:28

1 Answers1

1

jq is the choice:

$ echo $PRODUCT
PRODUCT3
$ cat json
{
    "DEVICE"     : "DESKTOP",
    "ACCOUNT"    : "test123",

    "PRODUCT1": {
        "URL"    : "https://product1.url:6080"
    },

    "PRODUCT2": {
        "URL"    : "https://testing.url.test:8090"
    },

    "PRODUCT3": {
        "URL"    : "https://start.url:18080"
    }
}
$ jq -r --arg p $PRODUCT '.[$p].URL' json
https://start.url:18080
Oliver Gaida
  • 1,722
  • 7
  • 14
  • Thanks Oliver for the answer. Is there any pure bash way? – Jitesh Sojitra Jul 20 '19 at 18:57
  • 1
    @JiteshSojitra, there is no robust, reliable pure-bash way, unless you write a standard-compliant JSON parser in pure bash. Which is something no reasonable person would do, because (1) bash's native data structures are less expressive than JSON is, so even if implemented 100% perfectly, such a tool couldn't do a perfect translation from JSON into standard native data structures; and (2) there are excellent tools already available -- not just jq, but also Python's built-in `json` module -- which it's easy to *use from* bash. – Charles Duffy Jul 20 '19 at 18:59
  • @OliverGaida, ...for future note, by the way -- in [How to Answer](https://stackoverflow.com/help/how-to-answer), see the "Answer Well-Asked Questions" section, and therein the bullet point regarding questions "which have been asked and answered many times before". Closing such questions instead of answering them helps us keep the answers all in one place, so we have the best possible answers all together rather than fragmented apart attached to different instances of the same question. – Charles Duffy Jul 20 '19 at 19:03
  • @Charles Duffy: sorry for that, i will check it out. Best regards – Oliver Gaida Jul 20 '19 at 19:06