title: Jq - calculate length of each array in JSON and update it
body: <p>I have the following JSON array</p>
  <pre><code>[
    {
      &quot;name&quot;: &quot;California&quot;,
      &quot;Data&quot;: {
        &quot;AB00001&quot;: [&quot;Los Angeles&quot;, &quot;San Francisco&quot;, &quot;Sacramento&quot;, &quot;Fresno&quot;, &quot;San Jose&quot;, &quot;Palo Alto&quot;]
      }
    },
    {
      &quot;name&quot;: &quot;Oregon&quot;,
      &quot;Data&quot;: {
        &quot;CD00002&quot;: [&quot;Portland&quot;, &quot;Salem&quot;, &quot;Hillsboro&quot;]
      }
    },
    {
      &quot;name&quot;: &quot;Washington&quot;,
      &quot;Data&quot;: {
        &quot;EF00003&quot;: [&quot;Seattle&quot;, &quot;Tacoma&quot;, &quot;Spokane&quot;, &quot;Bellevue&quot;]
      }
    }
  ]
  </code></pre>
  <p>With <code>jq '.[].Data[] | length'</code> I can get the length of each array, but I need to create <code>Length</code> key under <code>Data</code> object and assign to it the length of the array which is in the Data object. The result should look like the following:</p>
  <pre><code>[
      {
          &quot;name&quot;: &quot;California&quot;,
          &quot;Data&quot;: {
              &quot;ID00001&quot;: [&quot;Los Angeles&quot;, &quot;San Francisco&quot;, &quot;Sacramento&quot;, &quot;Fresno&quot;, &quot;San Jose&quot;, &quot;Palo Alto&quot;],
              &quot;Length&quot;: 6
          }
      },
      {
          &quot;name&quot;: &quot;Oregon&quot;,
          &quot;Data&quot;: {
              &quot;ID00002&quot;: [&quot;Portland&quot;, &quot;Salem&quot;, &quot;Hillsboro&quot;],
              &quot;Length&quot;: 3
          }
      },
      {
          &quot;name&quot;: &quot;Washington&quot;,
          &quot;Data&quot;: {
              &quot;ID00003&quot;: [&quot;Seattle&quot;, &quot;Tacoma&quot;, &quot;Spokane&quot;, &quot;Bellevue&quot;],
              &quot;Length&quot;: 4
          }
      }
  ]
  </code></pre>
  <p>The problem here is that in my example the object name holding the array (<code>Data</code> in my example) and the array name itself (<code>AB00001/CD00002/EF00003</code>) are not known in advance. However, the values of the <code>name</code> key is known. Also, the array might be empty, so in this case, the <code>Length</code> should be 0.</p>
  <p>So the algorithm pseudocode should be either of one as I've envisioned:</p>
  <pre><code>for the whole JSON file, 
  if the type is an array, 
  then assign it to the Length key created in the parent object of that array, 
  next
  </code></pre>
  <p>or</p>
  <pre><code>For the specific value in the name key, select,
  if the entry contains an array
  create Length key in the array's parent object, 
  assign the length of the array,
  select the next value of the name key
  </code></pre>
  <p>I tried to use with jq's <code>walk</code> or <code>..</code> for the first approach but didn't work.
  What are the alternatives?</p>