PSQL-检查JSON值是否具有特定属性

发布于 2025-02-10 16:46:49 字数 466 浏览 0 评论 0原文

我试图根据详细信息列的特定值删除表,该值是JSON类型。

该列有望具有这样的json值:

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

items中的对象可以具有name条目。我想删除那些没有该条目的人。

注意:所有项目中的所有对象都具有相同的条目,因此所有对象都将拥有或没有name entry

I'm trying to delete rows from a table depending on a specific value on a details column which is of json type.

The column is expected to have a json value like this one:

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

The objects inside items could have a name entry or not. 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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

找个人就嫁了吧 2025-02-17 16:46:49

您可以使用JSON路径表达式。

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

这检查至少有一个数组元素,该元素在其中名称不为空。请注意,这不会用具有“ name”:“”的数组元素删除行,


因为您不使用推荐的jsonb type(这是支持的jsonb type(所有Nifty JSON路径运算符),您需要将列投放为JSONB

You can use a JSON path expression.

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": ""


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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文