Skip to content

Commit 030d482

Browse files
Decode JSON columns without changing table row values (#3005)
Fixes #3003 --------- Co-authored-by: Custard <85372096+Muguett-DBY@users.noreply.github.com>
1 parent 2c5eb8e commit 030d482

3 files changed

Lines changed: 195 additions & 20 deletions

File tree

‎datasette/renderer.py‎

Lines changed: 50 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -6,26 +6,39 @@
66
error_body,
77
path_from_row_pks,
88
remove_infinites,
9-
sqlite3,
109
value_as_boolean,
1110
)
1211
from datasette.utils.asgi import Response
1312

1413

14+
def _load_json_value(value):
15+
try:
16+
return json.loads(value)
17+
except (TypeError, ValueError):
18+
return value
19+
20+
1521
def convert_specific_columns_to_json(rows, columns, json_cols):
22+
if not rows:
23+
return rows
24+
if columns is None:
25+
if not isinstance(rows[0], dict):
26+
return rows
27+
columns = rows[0].keys()
1628
json_cols = set(json_cols)
1729
if not json_cols.intersection(columns):
1830
return rows
1931
new_rows = []
2032
for row in rows:
21-
new_row = []
22-
for value, column in zip(row, columns):
23-
if column in json_cols:
24-
try:
25-
value = json.loads(value)
26-
except (TypeError, ValueError):
27-
pass
28-
new_row.append(value)
33+
if isinstance(row, dict):
34+
new_row = dict(row)
35+
for column in json_cols.intersection(row):
36+
new_row[column] = _load_json_value(row[column])
37+
else:
38+
new_row = [
39+
_load_json_value(value) if column in json_cols else value
40+
for value, column in zip(row, columns)
41+
]
2942
new_rows.append(new_row)
3043
return new_rows
3144

@@ -38,9 +51,23 @@ def json_renderer(request, args, data, error, truncated=None):
3851
json_cols = []
3952
if "_json" in args:
4053
json_cols = args.getlist("_json")
41-
if json_cols and "rows" in data and "columns" in data:
54+
object_keys = None
55+
pks = data.get("primary_keys")
56+
if (
57+
not error
58+
and args.get("_shape") == "object"
59+
and pks
60+
and any(pk in json_cols for pk in pks)
61+
):
62+
object_keys = []
63+
columns = data.get("columns")
64+
for row in data["rows"]:
65+
if columns and not isinstance(row, dict):
66+
row = dict(zip(columns, row))
67+
object_keys.append(path_from_row_pks(row, pks, False))
68+
if json_cols and "rows" in data:
4269
data["rows"] = convert_specific_columns_to_json(
43-
data["rows"], data["columns"], json_cols
70+
data["rows"], data.get("columns"), json_cols
4471
)
4572

4673
# unless _json_infinity=1 requested, replace infinity with None
@@ -61,11 +88,10 @@ def json_renderer(request, args, data, error, truncated=None):
6188
if shape == "arrayfirst":
6289
if not data["rows"]:
6390
data = []
64-
elif isinstance(data["rows"][0], sqlite3.Row):
65-
data = [row[0] for row in data["rows"]]
66-
else:
67-
assert isinstance(data["rows"][0], dict)
91+
elif isinstance(data["rows"][0], dict):
6892
data = [next(iter(row.values())) for row in data["rows"]]
93+
else:
94+
data = [row[0] for row in data["rows"]]
6995
elif shape in ("objects", "object", "array"):
7096
columns = data.get("columns")
7197
rows = data.get("rows")
@@ -83,8 +109,12 @@ def json_renderer(request, args, data, error, truncated=None):
83109
)
84110
else:
85111
object_rows = {}
86-
for row in data["rows"]:
87-
pk_string = path_from_row_pks(row, pks, not pks)
112+
for index, row in enumerate(data["rows"]):
113+
pk_string = (
114+
object_keys[index]
115+
if object_keys is not None
116+
else path_from_row_pks(row, pks, not pks)
117+
)
88118
object_rows[pk_string] = row
89119
data = object_rows
90120
if shape_error:
@@ -96,10 +126,10 @@ def json_renderer(request, args, data, error, truncated=None):
96126
elif shape == "arrays":
97127
if not data["rows"]:
98128
pass
99-
elif isinstance(data["rows"][0], sqlite3.Row):
100-
data["rows"] = [list(row) for row in data["rows"]]
101-
else:
129+
elif isinstance(data["rows"][0], dict):
102130
data["rows"] = [list(row.values()) for row in data["rows"]]
131+
else:
132+
data["rows"] = [list(row) for row in data["rows"]]
103133
else:
104134
status_code = 400
105135
data = error_body(f"Invalid _shape: {shape}", status_code)

‎docs/json_api.rst‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -297,6 +297,9 @@ query string arguments:
297297
JSON. Without this argument those columns will be returned as JSON objects
298298
that have been double-encoded into a JSON string value.
299299
300+
With ``_shape=object``, the object keys still use the original database
301+
primary-key values, even when a primary-key column is decoded using ``_json``.
302+
300303
Compare `this query without the argument <https://fivethirtyeight.datasettes.com/fivethirtyeight.json?sql=select+%27{%22this+is%22%3A+%22a+json+object%22}%27+as+d&_shape=array>`_ to `this query using the argument <https://fivethirtyeight.datasettes.com/fivethirtyeight.json?sql=select+%27{%22this+is%22%3A+%22a+json+object%22}%27+as+d&_shape=array&_json=d>`_
301304
302305
``?_json_infinity=on``

‎tests/test_api.py‎

Lines changed: 142 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -780,6 +780,148 @@ async def test_settings_json(ds_client):
780780
]
781781

782782

783+
@pytest.mark.asyncio
784+
@pytest.mark.parametrize("endpoint", ["table", "query"])
785+
@pytest.mark.parametrize("include_columns", [False, True])
786+
@pytest.mark.parametrize(
787+
"shape", ["objects", "object", "array", "arrayfirst", "arrays"]
788+
)
789+
async def test_json_columns_with_output_shapes(endpoint, include_columns, shape):
790+
if endpoint == "query" and shape == "object":
791+
pytest.skip("Object shape requires a table primary key")
792+
ds = Datasette()
793+
db = ds.add_memory_database("json_shapes")
794+
await db.execute_write("CREATE TABLE t (value text, id integer primary key)")
795+
await db.execute_write("INSERT INTO t VALUES (?, ?)", ['["a", "b"]', 1])
796+
parameters = {"_json": "value", "_shape": shape}
797+
if include_columns:
798+
parameters["_extra"] = "columns"
799+
if endpoint == "query":
800+
parameters["sql"] = "SELECT value, id FROM t"
801+
path = "/json_shapes/-/query.json"
802+
else:
803+
path = "/json_shapes/t.json"
804+
try:
805+
response = await ds.client.get(path + "?" + urllib.parse.urlencode(parameters))
806+
assert response.status_code == 200
807+
result = response.json()
808+
row = {"value": ["a", "b"], "id": 1}
809+
if shape == "object":
810+
assert result == {"1": row}
811+
elif shape == "array":
812+
assert result == [row]
813+
elif shape == "arrayfirst":
814+
assert result == [["a", "b"]]
815+
elif shape == "arrays":
816+
assert result["rows"] == [[["a", "b"], 1]]
817+
else:
818+
assert result["rows"] == [row]
819+
if shape in ("objects", "arrays"):
820+
assert ("columns" in result) == include_columns
821+
finally:
822+
ds.close()
823+
824+
825+
@pytest.mark.asyncio
826+
@pytest.mark.parametrize("endpoint", ["table", "row"])
827+
@pytest.mark.parametrize(
828+
"value,expected", [('["a"]', ["a"]), ("not JSON", "not JSON"), (None, None)]
829+
)
830+
async def test_json_columns_preserve_other_values(endpoint, value, expected):
831+
ds = Datasette()
832+
db = ds.add_memory_database("json_values")
833+
await db.execute_write(
834+
"CREATE TABLE t (id integer primary key, value text, other text)"
835+
)
836+
await db.execute_write(
837+
"INSERT INTO t VALUES (?, ?, ?)", [1, value, '{"keep": true}']
838+
)
839+
path = "/json_values/t.json" if endpoint == "table" else "/json_values/t/1.json"
840+
try:
841+
response = await ds.client.get(path + "?_json=value")
842+
assert response.status_code == 200
843+
assert response.json()["rows"] == [
844+
{"id": 1, "value": expected, "other": '{"keep": true}'}
845+
]
846+
finally:
847+
ds.close()
848+
849+
850+
@pytest.mark.asyncio
851+
@pytest.mark.parametrize("include_columns", [False, True])
852+
@pytest.mark.parametrize("composite_key", [False, True])
853+
@pytest.mark.parametrize(
854+
"values",
855+
[
856+
[('"same"', "same"), ("same", "same")],
857+
[("null", None), ("None", "None")],
858+
[(' {"id":1}', {"id": 1})],
859+
[('["x"]', ["x"]), ("['x']", "['x']")],
860+
],
861+
)
862+
async def test_json_columns_object_preserves_primary_keys(
863+
include_columns, composite_key, values
864+
):
865+
ds = Datasette()
866+
db = ds.add_memory_database("json_keys")
867+
primary_key = "id, tenant" if composite_key else "id"
868+
await db.execute_write(
869+
f"CREATE TABLE t (id text, tenant text, payload text, primary key ({primary_key}))"
870+
)
871+
expected = {}
872+
for index, (raw_id, decoded_id) in enumerate(values):
873+
payload = f"row-{index}"
874+
await db.execute_write(
875+
"INSERT INTO t VALUES (?, ?, ?)", [raw_id, '"team"', payload]
876+
)
877+
key = tilde_encode(raw_id)
878+
if composite_key:
879+
key += "," + tilde_encode('"team"')
880+
expected[key] = {
881+
"id": decoded_id,
882+
"tenant": "team" if composite_key else '"team"',
883+
"payload": payload,
884+
}
885+
parameters = [("_shape", "object"), ("_json", "id")]
886+
if composite_key:
887+
parameters.append(("_json", "tenant"))
888+
if include_columns:
889+
parameters.append(("_extra", "columns"))
890+
try:
891+
response = await ds.client.get(
892+
"/json_keys/t.json?" + urllib.parse.urlencode(parameters)
893+
)
894+
assert response.status_code == 200
895+
assert response.json() == expected
896+
for key in expected:
897+
detail = await ds.client.get(f"/json_keys/t/{key}.json")
898+
assert detail.status_code == 200
899+
finally:
900+
ds.close()
901+
902+
903+
@pytest.mark.asyncio
904+
@pytest.mark.parametrize(
905+
"shape", ["objects", "object", "array", "arrayfirst", "arrays"]
906+
)
907+
async def test_json_columns_with_empty_results(shape):
908+
ds = Datasette()
909+
db = ds.add_memory_database("json_empty")
910+
await db.execute_write("CREATE TABLE t (id integer primary key, value text)")
911+
try:
912+
response = await ds.client.get(f"/json_empty/t.json?_json=value&_shape={shape}")
913+
assert response.status_code == 200
914+
result = response.json()
915+
if shape == "object":
916+
assert result == {}
917+
elif shape in ("array", "arrayfirst"):
918+
assert result == []
919+
else:
920+
assert result["rows"] == []
921+
finally:
922+
ds.close()
923+
924+
783925
@pytest.mark.asyncio
784926
@pytest.mark.parametrize(
785927
"extra_args,expected",

0 commit comments

Comments
 (0)