简体   繁体   English

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

[英]How do I parse the following JSON field? (PostgreSQL)

I seem to be unable to parse the following JSON field (named 'attributes') in the normal way:我似乎无法以正常方式解析以下 JSON 字段(名为“属性”):

select attributes -> 'foo' from schema.table

The JSON field has a key-date-value format I've never seen before. JSON 字段具有我以前从未见过的键-日期-值格式。

In Postgres, how would I parse this JSON field to select just the value of the barcode?在 Postgres 中,我如何将这个 JSON 字段解析为 select 只是条形码的值? So far, I've had to fallback on string parsing instead, which is unideal.到目前为止,我不得不转而使用字符串解析,这是不理想的。

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

Thanks a million!太感谢了!

You need to unnest the element of the array and then pick the one with the key = barcode :您需要取消嵌套数组的元素,然后选择带有key = barcode的元素:

select x.j ->> 'value'
from the_table
  cross join jsonb_array_elements(attributes) as x(j)
where x.j ->> 'key' = 'barcode'

If you are already using Postgres 12, this is a little bit easier as you can use a SQL/JSON path query如果您已经在使用 Postgres 12,这会更容易一些,因为您可以使用SQL/JSON 路径查询

select jsonb_path_query_first(attributes, '$[*] ? (@.key == "barcode").value') 
from data

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM