3

I have a table which includes jsonb column "details" with wrong data type as follow:

select id,details from products;

id |              details                
---+-----------------------------------------
 1 | {"price": "310", "supplier": "VendorA"}
 2 | {"price": "250", "supplier": "VendorB"}

Here I would like to change data type of "price" to integer which is stored as string currently. Desired result is as follows:

id |              details             
---+-----------------------------------------
 1 | {"price": 310, "supplier": "VendorA"}
 2 | {"price": 250, "supplier": "VendorB"}

I will appreciate if you can guide me how to achieve it?

1 Answer 1

3

You can cast the value to json number using the function to_jsonb():

select id, jsonb_set(details, '{price}', to_jsonb((details->>'price')::int))
from products

 id |               jsonb_set               
----+---------------------------------------
  1 | {"price": 310, "supplier": "VendorA"}
  2 | {"price": 250, "supplier": "VendorB"}
(2 rows)

The update statement may look like this:

update products
set details = jsonb_set(details, '{price}', to_jsonb((details->>'price')::int))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.