检查json类型列PostgreSQL中是否存在字段

Ale*_*u R 33 postgresql json

你如何检查jsonPostgres中的某个字段是否有某个元素?

我尝试过json->>'attribute' is not null但不起作用.

Rom*_*kar 56

用途->:

where (json->'attribute') is not null
Run Code Online (Sandbox Code Playgroud)

  • 存在 != 不为空 (5认同)
  • @Brendan `column->'attribute'` 仅当 json 路径不存在时才会产生 null。如果 `column->>'attribute'` 不存在,则返回 null,*或* 如果存在且值为 null,例如 `column = '{"attribute":null}'`。 (4认同)
  • @Chad 您可能必须将您的内容转换为正确的类型,执行 `where (myfield::json->'attribute') is not null`。 (2认同)
  • 仅供参考,不需要括号。 (2认同)

Eug*_*kov 9

虽然有效。最好使用特殊运算符?

WHERE your_column_name::jsonb ? 'attribute'
Run Code Online (Sandbox Code Playgroud)

注意:仅适用于jsonb类型。

  • 请注意,“?”运算符仅适用于顶级属性。如果你想检查 json 结构中是否存在较低的路径,请根据 Roman 的答案执行 `.. where column->'foo'->'bar'->'baz' is not null`。 (4认同)
  • 如果该列已经是 jsonb 类型,则不需要强制转换。对于 jsonb 列,这是一个更清晰的答案。 (3认同)
  • @RocketAppliances:当您使用“->”时,它将检查“your_column_name.attribute”的值是否存在,但“?”将检查“attribute”的现有值。那是。例如:`obj.field IS NULL`将返回`true`,但是`obj ? 'field'` 将返回 `false` (3认同)