1

Im getting error while updating JSON data

CREATE TABLE testTable
AS
  SELECT $${
    "id": 1,
    "value": 100
  }$$::jsonb AS jsondata;

and I want to update value to 101 by adding 1, after visiting many websites I found this statement

UPDATE testTable
SET jsondata = JSONB_SET(jsondata, '{value}', (jsondata->>'value')::int + 1);

but above one is giving error "cannot convert jsonb to int"

and my expected output is

{
    "id": 1,
    "value": 101
}
3
  • please post the table schema for testTable Commented Apr 10, 2017 at 17:59
  • testTable contain only one column jsondata type JSONB Commented Apr 10, 2017 at 18:23
  • postgresql should not be reporting "cannot convert jsonb to int" then Commented Apr 10, 2017 at 19:13

1 Answer 1

6

Look at the signature of jsonb_set (using \df jsonb_set)

   Schema   |   Name    | Result data type |                                  Argument data types                                   |  Type  
------------+-----------+------------------+----------------------------------------------------------------------------------------+--------
 pg_catalog | jsonb_set | jsonb            | jsonb_in jsonb, path text[], replacement jsonb, create_if_missing boolean DEFAULT true | normal

What you want is this..

UPDATE testTable
  SET jsondata = jsonb_set(
    jsondata,
    ARRAY['value'],
    to_jsonb((jsondata->>'value')::int + 1)
  )
;
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.