0

I am trying to make an array with Jq

My code is:

all='('$(cat players_temp.json | jq -r  '.item1.items[1].firstName, .item1.items[1].lastName')')'

It gives the output

$ echo $all
(Luka Modrić)

$ echo $all[1]
(Luka Modrić)[1]

as you can see the array does not work like an array. I was expecting this:

$ echo $all[1]
Modrić
2
  • Please follow the minimal reproducible example guidelines as closely as possible. Here, some (possibly simplified) version of players_temp.json would be helpful. Commented Oct 18, 2019 at 2:23
  • While I don't know what your variable really looks like, notice that array element access in Bash looks like ${all[1]}, not $all[1]. Commented Oct 18, 2019 at 2:25

1 Answer 1

2

To create a bash array from jq output, see e.g. the following SO page:

How do I convert json array to bash array of strings with jq?

To understand why your approach failed, consider this transcript of a session with the bash shell:

$ all='('"Luka Modrić"')'
$ echo $all
(Luka Modrić)

$ echo $all[1]
(Luka Modrić)[1]

This essentailly shows that your question has nothing to do with jq at all.

If you want $all to be an array consisting of the two strings "Luka" and "Modrić" then you could write:

$ all=("Luca" "Modrić")
echo ${all[1]}
Modrić
$ echo ${all[0]}
Luca

Notice the correct bash syntax for arrays, and that the index origin is 0.

Summary

  1. See the above-mentioned SO page for alternative ways to create a bash array from jq output.

  2. The syntax for creating a bash array from a collection of strings can be summarized by:

    ary=( v0 ... )

  3. If ary is a bash array, ${ary[i]} is the i-th element, where i ranges from 0 to ${#ary[@]} - 1.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! I've tried to use the function get_json_array that mentioned in the link you provided. Unfortunately i get error 'command not found'. Am i missing something?
@Muq - Apparently so. It's just a place-holder for a process that produces a JSON array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.