Re: Returning values from an array of JSONB objects.

From: Vitaly Burovoy <vitaly(dot)burovoy(at)gmail(dot)com>
To: sighup <rts(at)sighup(dot)eu>
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: Returning values from an array of JSONB objects.
Date: 2016-04-13 10:42:30
Message-ID: CAKOSWNmcTYU460YTUSdVFoETpHpN2DMX_KRHO86vUHC3Wc=7cg@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On 4/13/16, sighup <rts(at)sighup(dot)eu> wrote:
> Hi, please excuse either my stupidity or naivety regarding this but I'm
> a bit confused. Give the following basic table structure :
>
> TABLE Data (
> ID INT NOT NULL,
> Markers jsonb NOT NULL
> );
>
> And the following data:
>
> INSERT INTO Data (ID, Markers) VALUES(1, '[ {"idle": true, "items": 8,
> "done": 0}, {"idle": true, "items": 8, "done": 0}]') ;
>
> How can I extract the value of the 'items' key either as two rows and or
> a sum of both.

You should use a proper function "jsonb_populate_recordset" [1].

> I had thought that :
>
> SELECT Markers->'items' AS Items FROM Data WHERE (ID = X) ;
>
> would have done the job but all I get is an empty column,

If course you get empty result because the operator "->" is "Get JSON
array *element*".

> of course using :
>
> SELECT Markers->0->'items' AS Items FROM Data WHERE (ID = X) ;
>
> Produces a single row but isn't exactly what I want.I have of course
> searched but not found a definitive answer, or maybe that should read
> 'one I can understand'.
>
> I'm using PostgreSQL 9.5 on Linux with pgAdmin III on Mac.
>
> --
> Bill

[1] http://www.postgresql.org/docs/9.5/static/functions-json.html
--
Best regards,
Vitaly Burovoy

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Vitaly Burovoy 2016-04-13 10:53:35 Re: Returning values from an array of JSONB objects.
Previous Message sighup 2016-04-13 10:30:34 Returning values from an array of JSONB objects.