title: How to convert arbitrary simple JSON to CSV using jq?
body: <p>Using <a href="https://stedolan.github.io/jq/">jq</a>, how can arbitrary JSON encoding an array of shallow objects be converted to CSV?</p>
  
  <p>There are plenty of Q&amp;As on this site that cover specific data models which hard-code the fields, but answers to this question should work given any JSON, with the only restriction that it's an array of objects with scalar properties (no deep/complex/sub-objects, as flattening these is another question). The result should contain a header row giving the field names. Preference will be given to answers that preserve the field order of the first object, but it's not a requirement. Results may enclose all cells with double-quotes, or only enclose those that require quoting (e.g. 'a,b').</p>
  
  <h2>Examples</h2>
  
  <ol>
  <li><p>Input:</p>
  
  <pre><code>[
      {"code": "NSW", "name": "New South Wales", "level":"state", "country": "AU"},
      {"code": "AB", "name": "Alberta", "level":"province", "country": "CA"},
      {"code": "ABD", "name": "Aberdeenshire", "level":"council area", "country": "GB"},
      {"code": "AK", "name": "Alaska", "level":"state", "country": "US"}
  ]
  </code></pre>
  
  <p>Possible output:</p>
  
  <pre><code>code,name,level,country
  NSW,New South Wales,state,AU
  AB,Alberta,province,CA
  ABD,Aberdeenshire,council area,GB
  AK,Alaska,state,US
  </code></pre>
  
  <p>Possible output:</p>
  
  <pre><code>"code","name","level","country"
  "NSW","New South Wales","state","AU"
  "AB","Alberta","province","CA"
  "ABD","Aberdeenshire","council area","GB"
  "AK","Alaska","state","US"
  </code></pre></li>
  <li><p>Input:</p>
  
  <pre><code>[
      {"name": "bang", "value": "!", "level": 0},
      {"name": "letters", "value": "a,b,c", "level": 0},
      {"name": "letters", "value": "x,y,z", "level": 1},
      {"name": "bang", "value": "\"!\"", "level": 1}
  ]
  </code></pre>
  
  <p>Possible output:</p>
  
  <pre><code>name,value,level
  bang,!,0
  letters,"a,b,c",0
  letters,"x,y,z",1
  bang,"""!""",0
  </code></pre>
  
  <p>Possible output:</p>
  
  <pre><code>"name","value","level"
  "bang","!","0"
  "letters","a,b,c","0"
  "letters","x,y,z","1"
  "bang","""!""","1"
  </code></pre></li>
  </ol>