0

I'd like to iterate over an array inside a JSON file by index using bash jq, and get for example only the name from each object inside that array:

{
  "items": [
    {
      "name": "item1",
      "year": "2021"
    },
    {
      "name": "item2",
      "year": "2020"
    }
  ]
}

Any ideas on how to achieve something like this?

item1name=`jq '.items'<???????> object.json | sed "s/\"//g"`
1
  • 1
    jq is not part of bash. Commented Dec 6, 2021 at 18:00

1 Answer 1

1

You can use

jq -r '.items[] | .name' object.json

where -r option is used to remove double quotes wrapping up the name values.

Demo

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

3 Comments

Thank you! Is there any way that I can save this array of names which I can then use dynamically by using an index of somehow?
After Googling for Bash arrays, I came across this approach to iterate over arrays: for i in ${!names[@]}; do printf "${names[$i]}" printf "\n" done
Use the bash readarray command to capture the lines of output from jq into a bash array. readarray -t names < <(jq -r ...)

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.