【问题标题】:Get value from JSON array in postgres从 postgres 中的 JSON 数组中获取值
【发布时间】:2021-11-20 15:17:51
【问题描述】:

我的 Postgres 数据库中有一个奇怪的 JSON 数组,没有大括号。它的数据类型是 Text,所以我猜我需要将它转换成 JSON。

看起来像这样,并且可以逐行更改。

    [
  [
    "-",
    "name",
    "Gates"
  ],
  [
    "-",
    "name_1",
    null
  ],
  [
    "-",
    "name_2",
    null
  ],
  [
    "-",
    "na_cd",
    null
  ],
  [
    "-",
    "class_cd",
    null
  ],
  [
    "-",
    "reference",
    "190955"
  ],
  [
    "-",
    "lang_cd",
    "en"
  ],
  [
    "-",
    "uid_nr",
    null
  ],
  [
    "-",
    "id",
    19000
  ],
  [
    "-",
    "firstname",
    "Bill"
  ],
  [
    "-",
    "spare",
    null
  ]
]

我需要的是找到并打印 ID(如果有)。在本例中为 19000。

有人可以帮忙怎么做吗?

【问题讨论】:

  • 如果有多个数组元素带有id 怎么办?

标签: arrays json postgresql postgresql-10


【解决方案1】:

基本上,您应该使用两次jsonb_array_elements(),分别用于主数组和过滤后的元素(这也是一个数组)。

select value::numeric as result
from (
    select elem
    from the_data
    cross join jsonb_array_elements(col) as main(elem)
    where elem ? 'id'
    ) s
cross join jsonb_array_elements(elem)
where jsonb_typeof(value) = 'number'

Db<>Fiddle.试试吧

但是,如果您想从嵌套数组中准确获取第三个值,查询可能会更简单(注意数组元素从 0 开始索引):

select (elem->2)::numeric as result
from the_data
cross join jsonb_array_elements(col) as main(elem)
where elem ? 'id'

Db<>Fiddle.

【讨论】:

    【解决方案2】:

    如果您使用的是 Postgres 12 或更高版本,并且您所追求的值始终位于第三个数组元素处,则可以使用 SQL/JSON 路径表达式:

    select jsonb_path_query_first(the_column, '$ ? (@[*] == "id")[2]')::int
    from the_table
    

    这假定该列被定义为jsonb(它应该是)。如果不是,则需要强制转换:the_column::jsonb

    【讨论】:

    • 错误:函数 jsonb_path_query_first(jsonb, unknown) 不存在 :(
    • @user2210516:我假设您使用的是当前的 Postgres 版本。你用的是哪个版本?
    • PostgreSQL 10.18
    猜你喜欢
    • 2020-09-28
    • 2020-03-07
    • 1970-01-01
    • 2020-10-14
    • 2013-12-24
    • 1970-01-01
    • 2022-08-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多