1

Say I have in Postgres stored in JSON field called “data” like this

{
    "CUSTA": {
        "name": "Customer A",
    },
    "CUSTB": {
        "name": "Customer B",
    },
    "CUSTC": {
        "name": "Customer C",
    }
}

How can I query to return the record that contains the key “CUSTA” ? or even better the value of “CUSTA” which is "name": "Customer A"

trying to do something like this but obviously i cant use the keyword key

SELECT * FROM invoices WHERE data->>key = 'CUSTA';

1 Answer 1

3
select '{
    "CUSTA": {
        "name": "Customer A"
    },
    "CUSTB": {
        "name": "Customer B"
    },
    "CUSTC": {
        "name": "Customer C"
    }
}'::json#>>'{CUSTA}';
           ?column?
------------------------------
 {                           +
         "name": "Customer A"+
     }
(1 row)

note: you have trailing commas after name:customer x, which is not proper json. For your query, you would probably do something like:

select data#>>'{CUSTA}' from invoices;

or, if data isn't already a json field:

select data::json#>>'{CUSTA}' from invoices;

I don't understand why any invoice would have more than one customer though.

-g

Sign up to request clarification or add additional context in comments.

3 Comments

thanks, that works, actually its not invoice but customer table. so this is the actual sql statement - select data::json#>>'{CUSTA}' from customers; BTW, if i wanted to get the row with all the fields how do i do that ?
this works "select id,company_id, data::json#>>'{CUSTA}' from customers;" but it has this unknown column ?column?
add as mycolumn after the '{CUSTA}' to rename the column, like: "select id,company_id, data::json#>>'{CUSTA}' as mycolumn from customers;"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.