简体   繁体   中英

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.

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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