2

here is my code

curl random args
"link" | jq

and gives it gives is

{
  "id": "961438154596153411",
  "username": "testing",
  "avatar": "a9000496add364b16af27e2f583a2e1e0f",
  "discriminator": "1"
}

how would i save that as a bash variables so i could just do like echo "$id" and it gives me 961438154596153411 or echo "$username" testing

Solved Note: a better way of doing this is saving the curl input as json and then using that with jq so you dont have to request stuff multiple times (sorry if this is a dumb question im new to bash and jq)

ARatChicken
  • 23
  • 1
  • 1
  • 4
  • 4
    Does this answer your question? [JSON array to bash variables using jq](https://unix.stackexchange.com/questions/413878/json-array-to-bash-variables-using-jq) – Romeo Ninov Feb 17 '22 at 06:45

1 Answers1

3

To extract 961438154596153411 from the json, pipe the file in jq '.id'

Example:

$ jq '.id' << EOF
{
  "id": "961438154596153411",
  "username": "testing",
  "avatar": "a9000496add364b16af27e2f583a2e1e0f",
  "discriminator": "1"
}
EOF

outputs

"961438154596153411"

If you want it without the quotes, use -r for raw data.

All togeather, to put that number into a bash variable, I'd do this:

$ id=$(curl random args "link" | jq -r ".id")
$ echo "$id"
961438154596153411
Stewart
  • 12,628
  • 1
  • 37
  • 80
  • Facing an issue if the value contains space. ex. if the value is `"John Doe"`, I get just `"John` – Rumit Patel Jul 27 '22 at 15:19
  • @RumitPatel It sounds like you have a missing quotes issue. `jq '.id' <<< '{"id":"john doe"}'` indeed returns `"john doe"`. And `jq -r '.id' <<< '{"id":"john doe"}'` returns `john doe`. That would be a `bash` issue, not a `jq` issue. – Stewart Jul 27 '22 at 18:58