简体   繁体   English

psql - 检查 json 值是否具有特定属性

[英]psql - Check if json value has specific property

I'm trying to delete rows from a table depending on a specific value on a details column which is of json type.我正在尝试根据json类型的details列上的特定值从表中删除行。

The column is expected to have a json value like this one:该列应该有一个像这样的json值:

{
  "tax": 0, 
  "note": "", 
  "items": [
     {
       "price": "100", 
       "quantity": "1", 
       "description": "Test"
     }
  ]
}

The objects inside items could have a name entry or not. items内的对象可以有name条目,也可以没有。 I'd like to delete those that don't have that entry.我想删除那些没有那个条目的。

NOTE: All objects inside items have the same entries so all of them will have or will not have the name entry注意:项目内的所有对象都具有相同的条目,因此它们都将具有或不具有name条目

You can use a JSON path expression.您可以使用 JSON 路径表达式。

delete from the_table
where details::jsonb @@ '$.items[*].name <> ""'

This checks if there is at least one array element where the name is not empty.这将检查是否存在至少一个名称不为空的数组元素。 Note that this wouldn't delete rows with an array element having "name": ""请注意,这不会删除具有"name": ""数组元素的行


As you didn't use the recommended jsonb type (which is the one that supports all the nifty JSON path operators), you need to cast the column to jsonb .由于您没有使用推荐的jsonb类型(它支持所有漂亮的 JSON 路径运算符),您需要将该列强制转换为jsonb

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

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