0

Using our new API I am trying to extract several lines from the results of the API call and put those results into a bash array. Can anyone help me with this please. This is an example of the API output:

{
    "id": "1l2k3j",
    "createDate": "2015-03-06T03:40:29.000Z",
    "accountId": "12345",
    "url": "www.google.com",
  },
  {
    "id": "z0x99c",
    "createDate": "2015-03-06T03:43:04.000Z",
    "accountId": "12345",
    "url": "www.yahoo.com",
  },

I need to put the ids (for example: z0x99c) into a bash array.

Atomiklan
  • 5,164
  • 11
  • 40
  • 62

2 Answers2

2
array=($(tr -d '",' < file | awk '/id:/ {print $2}'))

or with GNU sed:

array=($(sed -n 's/.*"id": "\(.*\)".*/\1/p' file))

or with GNU grep:

array=($(grep -oP 'id": "\K[^"]*' file))

echo ${array[@]}

Output:

1l2k3j z0x99c
Cyrus
  • 84,225
  • 14
  • 89
  • 153
0

Depending on how you obtain this output,

array=($(curl http://api.example.com/boink | jq -r '.id'))
tripleee
  • 175,061
  • 34
  • 275
  • 318
  • That may work! I do something very similar. I pipe it into a python parser to make it more human readable, but I guess that's no longer necessary in this case. – Atomiklan Mar 24 '15 at 21:56
  • jq: command not found – Atomiklan Mar 24 '15 at 21:57
  • It's not (yet!?) a standard utility, but it's widely available. If you don't have it packaged for your platform already, it's a simple job to download and install it from http://stedolan.github.io/jq/ – tripleee Mar 24 '15 at 21:58
  • See the link to the proposed duplicate for a plethora of alternatives, including rolling your own JSON parser from an elephant's tusk and some second-rate paper clips. – tripleee Mar 24 '15 at 21:59
  • How about python json parser? – Atomiklan Mar 24 '15 at 22:01
  • curl http://api.example.com/boink | python -m json.tool – Atomiklan Mar 24 '15 at 22:01