Unix & Linux
bash ubuntu shell-script array json
Updated Thu, 28 Jul 2022 23:38:25 GMT

parse one field from an JSON array into bash array


I have a JSON output that contains a list of objects stored in a variable. (I may not be phrasing that right)

[
  {
    "item1": "value1",
    "item2": "value2",
    "sub items": [
      {
        "subitem": "subvalue"
      }
    ]
  },
  {
    "item1": "value1_2",
    "item2": "value2_2",
    "sub items_2": [
      {
        "subitem_2": "subvalue_2"
      }
    ]
  }
]

I need all the values for item2 in a array for a bash script to be run on ubuntu 14.04.1.

I have found a bunch of ways to get the entire result into an array but not just the items I need




Solution

Using :

$ cat json
[
  {
    "item1": "value1",
    "item2": "value2",
    "sub items": [
      {
        "subitem": "subvalue"
      }
    ]
  },
  {
    "item1": "value1_2",
    "item2": "value2_2",
    "sub items_2": [
      {
        "subitem_2": "subvalue_2"
      }
    ]
  }
]

CODE:

arr=( $(jq -r '.[].item2' json) )
printf '%s\n' "${arr[@]}"

OUTPUT:

value2
value2_2




Comments (5)

  • +1 – Have you tried something ? — Jan 07, 2015 at 00:13  
  • +2jq . <<< "$json" it's shell (bash) related, non specific to jq — Jan 07, 2015 at 00:23  
  • +1 – Missing parentheses : arr=( $(...) ) — Jan 07, 2015 at 00:35  
  • +5 – Great jq command, but please don't parse command output into an array with arr=( $(...) ) (even though it happens to work with the sample input): it doesn't work as intended with embedded or leading/trailing whitespace and can result in accidental globbing. — Jul 14, 2016 at 05:21  
  • +2 – @GillesQuenot, ...would you an accept an edit fixing the shell end of this to either not depend on word-splitting, or explicitly setting IFS and disabling globbing to make that word-splitting reliable? — Feb 01, 2019 at 14:15