title: Using jq, Flatten Arbitrary JSON to Delimiter-Separated Flat Dictionary
body: <p>I'm looking to transform JSON using <code>jq</code> to a delimiter-separated and flattened structure.</p>
  
  <p>There have been attempts at this. For example, <a href="https://stackoverflow.com/questions/37540717/flatten-nested-json-using-jq">Flatten nested JSON using jq</a>.</p>
  
  <p>However the solutions on that page fail if the JSON contains arrays. For example, if the JSON is:</p>
  
  <pre><code>{"a":{"b":[1]},"x":[{"y":2},{"z":3}]}
  </code></pre>
  
  <p>The solution above will fail to transform the above to:</p>
  
  <pre><code>{"a.b.0":1,"x.0.y":2,"x.1.z":3}
  </code></pre>
  
  <p>In addition, I'm looking for a solution that will also allow for an arbitrary delimiter. For example, suppose the space character is the delimiter.  In this case, the result would be:</p>
  
  <pre><code>{"a b 0":1,"x 0 y":2,"x 1 z":3}
  </code></pre>
  
  <p>I'm looking to have this functionality accessed via a Bash (4.2+) function as is found in CentOS 7, something like this:</p>
  
  <pre><code>flatten_json()
  {
      local JSONData="$1"
      # jq command to flatten $JSONData, putting the result to stdout
      jq ... &lt;&lt;&lt;"$JSONData"
  }
  </code></pre>
  
  <p>The solution should work with all JSON data types, including <em>null</em> and <em>boolean</em>. For example, consider the following input:</p>
  
  <pre><code>{"a":{"b":["p q r"]},"w":[{"x":null},{"y":false},{"z":3}]}
  </code></pre>
  
  <p>It should produce:</p>
  
  <pre><code>{"a b 0":"p q r","w 0 x":null,"w 1 y":false,"w 2 z":3}
  </code></pre>