Export option: _shape=array&_nl=on for newline-delimited JSON

This commit is contained in:
Simon Willison 2019-01-27 17:40:23 -08:00
commit b5dd83981a
6 changed files with 58 additions and 11 deletions

View file

@ -140,7 +140,13 @@
{% if display_rows %}
<div id="export" class="advanced-export">
<h3>Advanced export</h3>
<p>JSON shape: <a href="{{ url_json }}">default</a>, <a href="{{ append_querystring(url_json, '_shape=array') }}">array</a>{% if primary_keys %}, <a href="{{ append_querystring(url_json, '_shape=object') }}">object</a>{% endif %}</p>
<p>JSON shape:
<a href="{{ url_json }}">default</a>,
<a href="{{ append_querystring(url_json, '_shape=array') }}">array</a>,
<a href="{{ append_querystring(url_json, '_shape=array&_nl=on') }}">newline-delimited</a>{% if primary_keys %},
<a href="{{ append_querystring(url_json, '_shape=object') }}">object</a>
{% endif %}
</p>
<form action="{{ url_csv_path }}" method="get">
<p>
CSV options:

View file

@ -432,10 +432,18 @@ class BaseView(RenderMixin):
headers = {}
if self.ds.cors:
headers["Access-Control-Allow-Origin"] = "*"
# Handle _nl option for _shape=array
nl = request.args.get("_nl", "")
if nl and shape == "array":
body = "\n".join(json.dumps(item) for item in data)
content_type = "text/plain"
else:
body = json.dumps(data, cls=CustomJSONEncoder)
content_type = "application/json"
r = response.HTTPResponse(
json.dumps(data, cls=CustomJSONEncoder),
body,
status=status_code,
content_type="application/json",
content_type=content_type,
headers=headers,
)
else: