I have a table with two columns, containing an ID and a JSON object (jsonb). Each json object contains several values (e.g. urls) somewhere nested inside the object. I can use jsonb_path_query to extract all those values using [*], but they are returned as one value per line. How can I aggregate the return values in a way that the resulting table has the same number of lines as the original?
Here is the example:
CREATE TABLE IF NOT EXISTS test (
oid integer,
object jsonb
);
INSERT INTO test
VALUES
(1, '{"links": [
{"title": "a", "url": "w"},
{"title": "b", "url": "x"}
]}'),
(2, '{"links": [
{"title": "c", "url": "y"},
{"title": "d", "url": "z"}
]}');
SELECT
oid,
jsonb_path_query(object, '$.links[*].url')
FROM test;
The select query returns the following table:
| oid | jsonb_path_query |
| --- | ---------------- |
| 1 | w |
| 1 | x |
| 2 | y |
| 2 | z |
However, I would like to get this:
| oid | jsonb_path_query |
| --- | ---------------- |
| 1 | [w,x] |
| 2 | [y,z] |