title: Dynamically add json object into array with jq
body: <p>Below is the template of my employee.json file</p>
  
  <pre><code>{
      "orgConfig": {
          "departments": []
      }
  }
  </code></pre>
  
  <p>where departments will have array of departments like below</p>
  
  <pre><code>{
      "name" : "physics",
      "id" : "1234",
      "head" : "abcd"
  }
  </code></pre>
  
  <p>similarly</p>
  
  <pre><code>{
      "name" : "chemistry",
      "id" : "3421",
      "head" : "xyz"
  }
  </code></pre>
  
  <p>so the final array structure i want to construct is as below</p>
  
  <pre><code>{
      "orgConfig": {
          "departments": [
              {
                  "name" : "physics",
                  "id" : "1234",
                  "head" : "abcd"
              },
              {
                  "name" : "chemistry",
                  "id" : "3421",
                  "head" : "xyz"
              },
              {
                  "name" : "Maths",
                  "id" : "4634",
                  "head" : "jklm"
              }
          ]
      }
  }
  </code></pre>
  
  <p>Below is the code where i am adding the json elements to an departments array dynamically</p>
  
  <pre><code>#!/bin/bash
  
  source department.properties   # will have departments=physiscs,chemistry,Maths,computers .. etc
  IFS=',' read -ra NAMES &lt;&lt;&lt; "$departmentsToImport"
  
  position=0
  for i in "${NAMES[@]}"; do
      #./jsonfiles will chemistry.json, physics.json, Maths.json etc
      value=`cat ./jsonfiles/$i.json`    
  
      if [ $position -eq 0 ]
      then
         cat employee.json | jq --arg value "$value" '.orgConfig.departments[0] |= .+ $value' &gt; tmp.json &amp;&amp; mv tmp.json employee.json
      else
         cat employee.json | jq --arg position "$position" value "$value" '.orgConfig.departments[$position] |= .+ $value' &gt; tmp.json &amp;&amp; mv tmp.json employee.json
      fi
      ((position++))
      rm -rf tmp.json
  done
  
  exit $?
  </code></pre>
  
  <p>but program throws below error</p>
  
  <pre><code>jq: error (at &lt;stdin&gt;:51): Cannot index array with string "1"
  </code></pre>
  
  <p>But if use direct index instead of variable position then it works fine.</p>
  
  <pre><code>cat employee.json | jq --argjson value "$value" '.orgConfig.departments[1] |= .+ $value' &gt; tmp.json &amp;&amp; mv tmp.json employee.json 
  </code></pre>
  
  <p>I do not know how many key value maps of departments i have. I cannot hard code the index. Any help to above problem and Dynamically add json object into array?</p>
  
  <p>Thanks</p>