1

Let's say I have this json format:

[
    {
       "firstName": "John", 
       "lastName": "Doe"
    }
]

and I want to delete the "lastName", how can I do that?

So far I have this query and it works, but the problem is it adds another array

UPDATE person
SET 
    field = jsonb_set(field::jsonb, 
    '{0}', 
    field::jsonb #- '{0,lastName}',
    false)

The result from my query above:

[
    [
       {
           "firstName": "John"
       }
    ]
]

The result that I want:

[
    {
       "firstName": "John"
    }
]
klin
  • 112,967
  • 15
  • 204
  • 232
mycoding213
  • 71
  • 2
  • 6
  • Simple answer: you can not ! If you want your desired result then you have to copy the thing without the parts you want deleted. You may set them to zero or undefined but they would still be there. – Thomas Ludewig Oct 25 '19 at 02:02
  • At least when you run over them with Object.keys(). The Name will remain. – Thomas Ludewig Oct 25 '19 at 02:03
  • Just a thought! How about deleting this record and adding a new one? i.e. No editing stuff – sam Oct 25 '19 at 02:11
  • You want to delete a record from a json object, not an array. Should fix your question's title. – Shawn Oct 25 '19 at 02:36

4 Answers4

1

Use the first element of the array (not the whole array) in the third parameter:

UPDATE person
SET 
    field = jsonb_set(field::jsonb, 
    '{0}', 
    (field::jsonb->0) - 'lastName',
    false)
klin
  • 112,967
  • 15
  • 204
  • 232
0

The unneeded jsonb_set is causing the problem in this case. Get rid of it.

UPDATE person
SET 
    field = field::jsonb #- '{0,lastName}'
jjanes
  • 37,812
  • 5
  • 27
  • 34
-1

You could try with REGEXP_REPLACE.

The super basic pattern would be something like "lastName":"[a-zA-Z]*".

For a better one please see regular expression for first and last name.

tymtam
  • 31,798
  • 8
  • 86
  • 126
-2

I can say it is impossible. Please don't try it.

Maosen Hu
  • 60
  • 5