我似乎无法以正常方式解析以下JSON字段(称为“属性”):
select attributes -> 'foo'
from schema.table
JSON字段具有我从未见过的键-日期-值格式。
在Postgres中,我如何解析此JSON字段以仅选择条形码的值?到目前为止,我不得不依靠字符串分析,这是不理想的。
[{"key": "amount", "date": "2019-08-01T13:39:50.823Z", "value": 10},
{"key": "userId", "date": "2019-08-01T13:39:50.823Z", "value":
"4e79a15b24174970a913b5c94c030068"},
{"key": "accountUuid", "date": "2019-08-01T13:39:50.823Z", "value":
"bd305700-b461-11e9-8153-adf1629b78f9"},
{"key": "transactionId", "date": "2019-08-01T13:39:50.823Z", "value":
"e04a4099-8038-4cdc-8024-86147f23c749"},
{"key": "paymentType", "date": "2019-08-01T13:39:50.823Z", "value":
"bank_transfer"},
{"key": "vendor", "date": "2019-08-01T13:39:50.823Z", "value":
"12512"},
{"key": "barcode", "date": "2019-08-01T13:39:50.823Z", "value":
"0298350928359829052"},
{"key": "expirationDate", "date": "2019-08-01T13:39:50.823Z","value":
"2019-08-11T00:00:00.000Z"},
{"key": "date", "date": "2019-08-01T13:39:50.823Z", "value":
"2019-08-01T13:39:50.823Z"}]
感谢一百万!
答案 0 :(得分:1)
您需要取消嵌套数组的元素,然后使用key = barcode
进行选择:
select x.j ->> 'value'
from the_table
cross join jsonb_array_elements(attributes) as x(j)
where x.j ->> 'key' = 'barcode'
如果您已经在使用Postgres 12,则可以轻松使用SQL/JSON path查询
select jsonb_path_query_first(attributes, '$[*] ? (@.key == "barcode").value')
from data