0

required help need get the name value from id my bash script cant get it to work

#!/bin/bash

array=( "111" "222" etc...)

for i in "${array[@]}"; do
   my_power=$(
      curl -s -X GET -H "Content-Type: application/json" http://website/list |
         jq -r '.magic[] | select(.id == "$i") | .name'
   )
   echo "$my_power"
   magic_array+=( "$my_power" )
done 

$magic_array is empty. The echo prints nothing.

curl -s -X GET -H "Content-Type: application/json" http://website/list 

outputs the following all on one line:

{
  "magic": [
    {
      "name": "fly",
      "links": {
        "self": "http://website/111"
      },
      "tags": null,
      "enabled": true,
      "id": "111",
      "description": null
    },
    {
      "name": "sleep",
      "links": {
        "self": "http://website/222"
      },
      "tags": null,
      "enabled": true,
      "id": "222",
      "description": null
    }
  ],
  "links": {
    "self": "http://website/list",
    "previous": null,
    "next": null
  }
}

Direct request from command line work perfect

$ curl -s -X GET -H "Content-Type: application/json" http://website/list |
   jq -r '.magic[] | select(.id == "111") | .name'
fly
ikegami
  • 367,544
  • 15
  • 269
  • 518
  • This might help: [Difference between single and double quotes in bash](http://stackoverflow.com/q/6697753/3776858) – Cyrus Dec 20 '20 at 17:10
  • If there are n items in the list, the approach shown in the Q will require n redundant calls to `curl` and n calls to jq, whereas only one call to each is required!!! – peak Dec 20 '20 at 17:52

1 Answers1

4

In the jq program, $i refers to the jq variable $i, not the bash variable $i.

jq -r --arg i "$i" '.magic[] | select(.id == $i) | .name'
ikegami
  • 367,544
  • 15
  • 269
  • 518