title: iterate over json array elements in postgresql
body: <p>I've got a json that looks like this</p>
  
  <pre><code>{
      "elements": [ "element1", "element2", "element3" ]
  }
  </code></pre>
  
  <p>I want to iterate over its element and print them.
  I do it like this</p>
  
  <pre><code>do $$
  declare
      datajson jsonb := '{
          "elements": [ "element1", "element2", "element3", "element4" ]
      }';
      element varchar(128);
  begin
      foreach element in array jsonb_array_elements(datajson-&gt;'elements')
      loop
          raise notice '%', element;
      end loop;
  end;
  $$;
  </code></pre>
  
  <p>But it fails with the error <code>query select jsonb_array_elements(datajson-&gt;'elements') returned more than one row</code>.</p>
  
  <p>What is the problem?</p>
  
  <p><strong>UPDATE</strong></p>
  
  <p>Tried this suggestion:</p>
  
  <pre><code>do $$
  declare
      datajson jsonb := '{
          "elements": [ "element1", "element2", "element3", "element4" ]
      }';
      element varchar(128);
  begin
      foreach element in array
          SELECT array_agg(jsonb_array_elements) FROM jsonb_array_elements(datajson-&gt;'elements')
      loop
          raise notice '%', element;
      end loop;
  end;
  $$;
  </code></pre>
  
  <p>But that just gives a syntax error:</p>
  
  <pre><code>ERROR:  42601: syntax error at or near "SELECT"
  LINE 7:     SELECT array_agg(jsonb_array_elements) FROM jsonb_array_...
              ^
  LOCATION:  scanner_yyerror, scan.l:1134
  </code></pre>
  
  <p>Trying to do this without using <code>FOR r IN (...)</code> and declaring a <code>RECORD</code> variable.</p>