【问题标题】:Query data inside an attribute array in a json column in Postgres 9.6在 Postgres 9.6 中的 json 列中查询属性数组内的数据
【发布时间】:2017-05-18 20:23:28
【问题描述】:

我有一个表说类型,它有一个 JSON 列,说位置看起来像这样:

{ "attribute":[
  {
    "type": "state",
    "value": "CA"
  },
  {
    "type": "distance",
    "value": "200.00"
  } ...
  ]
  } 

表中的每一行都有数据,并且都有“类型”:“状态”。我只想从表中的每一行中提取 "type": "state" 的值,并将其放入一个新列中。我检查了几个关于 SO 的问题,例如:

但无法正常工作。我不需要对此进行查询。我需要此列的值。如果我遗漏了什么,我会提前道歉。

【问题讨论】:

  • 总是在第一个数组元素中吗? type = state可以有多个数组元素吗?
  • 不在同一行内。每一行只有一个 type = state 的属性。

标签: sql json postgresql


【解决方案1】:
create table t(data json);
insert into t values('{"attribute":[{"type": "state","value": "CA"},{"type": "distance","value": "200.00"}]}'::json); 

select elem->>'value' as state
from t, json_array_elements(t.data->'attribute') elem
where elem->>'type' = 'state';
|状态 | | :---- | |加利福尼亚州 |

dbfiddle here

【讨论】:

    【解决方案2】:

    我主要使用 Redshift,它有一个内置函数来执行此操作。因此,如果您在那里,请检查一下。 redshift docs

    看起来 Postgres 有类似的功能集: https://www.postgresql.org/docs/current/static/functions-json.html

    我认为您需要将三个函数链接在一起才能完成这项工作。

    SELECT 
       your_field::json->'attribute'->0->'value'
    FROM
        your_table
    

    我正在尝试的是按键名提取 json,然后是按索引提取 json 数组(如果您的示例与完整数据一致,则始终是第一个),最后是按键名提取的另一个。

    编辑:让它适用于您的示例

    SELECT 
      '{ "attribute":[
      {
        "type": "state",
        "value": "CA"
      },
      {
        "type": "distance",
        "value": "200.00"
      }
      ]
      }'::json->'attribute'->0->'value'
    

    返回"CA"

    第二次编辑:嵌套查询 @McNets 是正确、更好的答案。但在这次潜水中,我发现你可以在 Postgres 中嵌套查询!太酷了!

    我将 json 作为文本字段存储在虚拟表中并成功运行:

    SELECT 
      (SELECT value FROM json_to_recordset(
        my_column::json->'attribute') as x(type text, value text)
      WHERE
        type = 'state'
        )
    FROM dummy_table
    

    【讨论】:

    • 谢谢@a_horse_with_no_name,但我不能依赖索引。它可以在数组中的任何位置。
    猜你喜欢
    • 1970-01-01
    • 2018-03-29
    • 2013-09-20
    • 2022-01-07
    • 2018-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-15
    相关资源
    最近更新 更多