query a json key in postgres json field

百般思念 提交于 2019-12-08 07:42:33

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!