1

What I do:

  1. RESPONSE_TEMPLATES=$(curl "https://maydomain.com/test)
  2. I get back JSON which looks like this:
    {
      "templateId": "test",
      "id": 1621030
    }
    {
      "templateId": "test1",
      "id": 5014
    }
    {
      "templateId": "test3",
      "id": 5015
    }
  1. echo $(${RESPONSE_TEMPLATES} | jq -r '.[]'| {templateId,id}')

Problem is that I always get error: [{"id":1386084,"templateId":"test: command not found

I do not know how I should write 3 steps so that it will display this as a string and not use after ""test: " as command.

RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
user2017319
  • 77
  • 3
  • 6
  • Does this answer your question? [How can pass the value of a variable to the standard input of a command?](https://stackoverflow.com/questions/4775548/how-can-pass-the-value-of-a-variable-to-the-standard-input-of-a-command) – oguz ismail Sep 20 '22 at 13:50
  • 2
    Also note that there is a typo in your code: the middle single quote `'` is superfluous. There should only be two of them: one at the beginning and one at the end of your jq filter. – pmf Sep 20 '22 at 14:02
  • 1
    @pmf, Thank you for pointing out but looks like OP's logic is also not correct here. Even we remove `'` its not printing anything when I run that command on my terminal. So along with how to pass shell variable to `jq` code, a running jq code is not there. Though OP tried well and Good that efforts are shared in question. – RavinderSingh13 Sep 20 '22 at 14:06
  • `$(${RESPONSE_TEMPLATES})` tries to execute the content of the variable as command. The variable contains a JSON document. To feed it to a different command via pipe, use `echo` or `printf '%s'` – knittl Sep 20 '22 at 14:06

1 Answers1

1

With your shown samples please try following jq code. Using -r option to enable raw-mode option of jq then in main block using select function to check if component .templateId is test if yes then print its related id component value.

echo "${RESPONSE_TEMPLATES}" | jq -r 'select(.templateId=="test").id'
RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
  • Thank you, this now works as expected. How the same thing would be done if I would like to save the result in a variable? – user2017319 Sep 20 '22 at 14:05
  • @user2017319, Do it like `var1=$(echo "${RESPONSE_TEMPLATES}" | jq -r 'select(.templateId=="test").id')` to save into a shell variable. – RavinderSingh13 Sep 20 '22 at 14:05