knirirr
knirirr

Reputation: 2807

Nested JSON query in postgres

I have some JSON along the following lines, the format of which cannot, unfortunately, be changed:

{ 
  "elements": {
    "nodes": [
      {
        "data": {
          "name": "Name here",
          "color": "#FFFFFF",
          "id": "n0"
        }
      }
    ]
  }
}

This is stored in a postgres database and I'd like to pull out records by means of the id embedded in the JSON above. So far I've tried stuff like this:

SELECT "data".* FROM "data" WHERE payload #>> '{elements,nodes,data,id}' = 'n0';

...without success; although this query runs it returns nothing. Can anyone suggest how this might be done?

Upvotes: 1

Views: 368

Answers (1)

Dzmitry Savinkou
Dzmitry Savinkou

Reputation: 5190

Create schema:

create table json (
    id serial primary key,
    data jsonb
);

insert into json (data) values (
'{ "elements": {
    "nodes": [
      {
        "data": {
          "name": "Name here",
          "color": "#FFFFFF",
          "id": "n0"
        }
      }
    ]
  }
}
'::jsonb);

Query itself:

select * from json js,jsonb_array_elements(data->'elements'->'nodes') as node 
 where node->'data'->>'id' = 'n0';

Upvotes: 1

Related Questions