title: Using python function within a bash script - to parse JSON
body: <p>I have a bash script that is aimed at parsing the JSON formatted data. I learned from an earlier query on this forum that bash is not good at parsing JSON, and so intend to use a python function to do the parsing:</p>
  
  <p>The following is the code snippet:</p>
  
  <pre><code>#!/bin/bash
  
  set -e
  
  declare -a data_id
  declare -a data_tid
  
  function parse_data () {
      python &lt;&lt;EOF
  import json
  parsed = json.loads('''${@}''')
  
  data_id = []
  data_tid = []
  for child in parsed['params']['children'][0]:
      print 'id: %s' % (child['data']['id'])
      data_id.append(child['data']['id'])
      print 'tid: %s' % (child['data']['tid'])
      data_tid.append(child['data']['tid'])
  EOF
  }
  
  json=$(get_json_output)
  parse_data $json
  </code></pre>
  
  <p>The data stored in 'json' would look like this:</p>
  
  <pre><code>{
      "cid": "1",
      "code": null,
      "error": null,
      "params": {
          "children": [
              {
                  "value": {
                      "id": "0123456789",
                      "tid": "a.b.c"
                  },
                  "data": {
                      "id": "0987654321",
                      "tid": "p.q.r"
                  },
                  "tid": "m.n.o.p",
              }
          ],
          "tid": "m.n.o.p"
      },
      "reason": null,
      "result": true
  }
  </code></pre>
  
  <p>I'd like the script to be able to extract the 'id' and 'tid' fields from under 'data', into separate arrays. But the script execution fails as follows:</p>
  
  <pre><code>root@ubuntu# ./abc.sh 
  Traceback (most recent call last):
    File "&lt;stdin&gt;", line 7, in &lt;module&gt;
  TypeError: string indices must be integers
  </code></pre>
  
  <p>Any idea on what's wrong? </p>