我如何解析以下JSON字段? (PostgreSQL)

问题描述 投票:0回答:1

我似乎无法以正常方式解析以下JSON字段(命名为'attributes'):

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"}]

谢谢百万!

sql json postgresql
1个回答
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
© www.soinside.com 2019 - 2024. All rights reserved.