问题
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:
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
来源:https://stackoverflow.com/questions/23697540/query-a-json-key-in-postgres-json-field