Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Recently upgraded to using PostgreSQL 9.3.1 to leverage the JSONfunctionalities. In my table I have a json type column that has a structure like this:

{
   "id": "123",
   "name": "foo",
   "emails":[
      {
        "id": "123",
        "address": "somethinghere"
      },
      {
        "id": "456",
        "address": "soemthing"
      }
   ]
} 

This is just dummy data for the purpose of the question.

Is it possible to query for a specific item in the emails array based on the id?
Pretty much: "return email where id=123)"?

share|improve this question

1 Answer 1

up vote 10 down vote accepted

Yes, that's possible:

SELECT *
FROM   tbl t, json_array_elements(t.json_col->'emails') AS elem
WHERE  elem->>'id' = 123;

tbl being your table name, json_col being the name of the JSON column.

More details in these related answers:
How do I query using fields inside the new PostgreSQL JSON datatype?

More about the implicit LATERAL JOIN here (last paragraph):
PostgreSQL unnest() with element number

If you need an index to support this kind of query:
Index For Finding Element in JSON array

share|improve this answer
    
Can you please check my question stackoverflow.com/questions/22527154/… –  Shamith c Mar 20 at 18:28

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.