<div dir="ltr"><p class="MsoNormal" style="margin:0in 0in 0.0001pt;font-size:11pt;font-family:Calibri,sans-serif">Just ran into an error creating a GeoJSON file and thought I
would share my fix.</p><p class="MsoNormal" style="margin:0in 0in 0.0001pt;font-size:11pt;font-family:Calibri,sans-serif"><br></p>

<p class="MsoNormal" style="margin:0in 0in 0.0001pt;font-size:11pt;font-family:Calibri,sans-serif">I generate GeoJSON files constantly from PG/PostGIS on a regular
schedule.  Typical uses are how much rain
has fallen, potential flooding and earthquakes near me in the past week.  Sometimes the answer is ‘none’ – i.e. haven’t
seen any earthquakes lately.  When this
happens, the typical code I use (<a href="https://gist.github.com/brambow/889aca48831e189a62eec5a70067bf8e">https://gist.github.com/brambow/889aca48831e189a62eec5a70067bf8e</a>)</p><p class="MsoNormal" style="margin:0in 0in 0.0001pt;font-size:11pt;font-family:Calibri,sans-serif">gives the result  </p><p class="MsoNormal" style="margin:0in 0in 0.0001pt;font-size:11pt;font-family:Calibri,sans-serif">{"type" : "FeatureCollection",  "features" : null}<br></p><p class="MsoNormal" style="margin:0in 0in 0.0001pt;font-size:11pt;font-family:Calibri,sans-serif"><br></p><p class="MsoNormal" style="margin:0in 0in 0.0001pt;font-size:11pt;font-family:Calibri,sans-serif">While this is valid JSON, QGIS and Leaflet will really complain about it.  What they want is </p><p class="MsoNormal" style="margin:0in 0in 0.0001pt;font-size:11pt;font-family:Calibri,sans-serif">  {"type" : "FeatureCollection",  "features" : [] }  <br></p><p class="MsoNormal" style="margin:0in 0in 0.0001pt;font-size:11pt;font-family:Calibri,sans-serif">so I just wrap the coalesce function around it like this:</p><p class="MsoNormal" style="margin:0in 0in 0.0001pt;font-size:11pt;font-family:Calibri,sans-serif"><br></p><p class="MsoNormal" style="margin:0in 0in 0.0001pt;font-size:11pt;font-family:Calibri,sans-serif">SELECT json_build_object('type', 'FeatureCollection',<br> 'features', COALESCE(<br>      json_agg(json_build_object('type', 'Feature', 'geometry', (st_asgeojson(foo.geom))::json,<br>            'properties', json_build_object('bar', foo.bar)))<br>      , '[]')<br>      ) AS json_build_object<br>   FROM foo;<br></p><p class="MsoNormal" style="margin:0in 0in 0.0001pt;font-size:11pt;font-family:Calibri,sans-serif"><br></p><p class="MsoNormal" style="margin:0in 0in 0.0001pt;font-size:11pt;font-family:Calibri,sans-serif">This generates what QGIS and Leaflet are looking for.</p></div>