Search code examples
postgresqljsonb

Selecting a subsection of jsonb


Given table events:

create table events (
  id integer,
  data jsonb
)

How would one construct a query such that we return only select keys in the results column?

say we had the record in the events table:

(1, {"a": 1, "b": 2})

Is it possible to return something like:

id | data
1  | {"b": 2}

Solution

  • Straightforward, using jsonb_build_object:

    create temporary table events(id, data) 
    as values (1, '{"a":1, "b":2, "c":"three"}'::jsonb);
    
    select id, jsonb_build_object(
      'b', data -> 'b', 
      'c', data -> 'c'
    ) from events; 
    
    id jsonb_build_object
    1 {"b": 2, "c": "three"}