Join the Stack Overflow Community
Stack Overflow is a community of 6.6 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

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?

share|improve this question
up vote 1 down vote accepted

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';
share|improve this answer
    
That works, thanks. Now to get ActiveRecord to generate such a query... – knirirr Sep 3 '15 at 16:27

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.