0

I have a table schema as follows:

DummyTable
-------------
someData JSONB

All my values will be a JSON object. For example, when you do a select * from DummyTable, it would look like

someData(JSONB)
------------------
{"values":["P1","P2","P3"],"key":"ProductOne"}
{"values":["P3"],"key":"ProductTwo"}

I want a query which will give me result set as follows:

[
  {
    "values": ["P1","P2","P3"],
    "key": "ProductOne"
  },
  {
    "values": ["P4"],
   "key": "ProductTwo"
  }
]

I'm using Postgres version 9.4.2. I looked at documentation page of the same, but could not find the query which would give the above result.

However, in my API, I can build the JSON by iterating over rows, but I would prefer query doing the same. I tried json_build_array, row_to_json on a result which would be given by select * from table_name, but no luck.

Any help would be appreciated.

Here is the link I looked for to write a query for JSONB

1 Answer 1

1

You can use json_agg or jsonb_agg:

create table dummytable(somedata jsonb not null);
insert into dummytable(somedata) values
  ('{"values":["P1","P2","P3"],"key":"ProductOne"}'),
  ('{"values":["P3"],"key":"ProductTwo"}');
select jsonb_pretty(jsonb_agg(somedata)) from dummytable;

Result:

[
    {
        "key": "ProductOne",
        "values": [
            "P1",
            "P2",
            "P3"
        ]
    },
    {
        "key": "ProductTwo",
        "values": [
            "P3"
        ]
    }
]

Although retrieving the data row by row and building on client side can be made more efficient, as the server can start to send data much sooner - after it retrieves first matching row from storage. If it needs to build the json array first, it would need to retrieve all the rows and merge them before being able to start sending data.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.