Loops/Foreach: Difference between revisions

Content added Content deleted
(→‎{{header|jq}}: iterables and strings)
Line 967: Line 967:


Sometimes it is necessary to use an alternative to ".[]". For example, one might want to generate an index along with the array elements. In such cases, the "range(m;n)" generator, which performs a similar role to C's "for(i=m; i<n; i++)", can be used for array. Here is how range/2 would be used to perform the task for an array:
Sometimes it is necessary to use an alternative to ".[]". For example, one might want to generate an index along with the array elements. In such cases, the "range(m;n)" generator, which performs a similar role to C's "for(i=m; i<n; i++)", can be used for array. Here is how range/2 would be used to perform the task for an array:
<lang jq>range(0; example|length) | example[.]</lang>
<lang jq>example | . as $a | range(0; length) | $a[.]</lang>
For JSON objects, the corresponding technique involves using <tt>keys</tt>, e.g.
For JSON objects, the corresponding technique involves using <tt>keys</tt>, e.g.
<lang jq>
<lang jq>