I am working on data in postgresql as in the following mytable with the fields id (type int) and val (type json):
| id | val |
|---|---|
| 1 | "null" |
| 2 | "0" |
| 3 | "2" |
The values in the json column val are simple JSON values, i.e. just strings with surrounding quotes and have no key.
I have looked at the SO post How to convert postgres json to integer and attempted something like the solution presented there
SELECT (mytable.val->>'key')::int FROM mytable;
but in my case, I do not have a key to address the field and leaving it empty does not work:
SELECT (mytable.val->>'')::int as val_int FROM mytable;
This returns NULL for all rows.
The best I have come up with is the following (casting to varchar first, trimming the quotes, filtering out the string "null" and then casting to int):
SELECT id, nullif(trim('"' from mytable.val::varchar), 'null')::int as val_int FROM mytable;
which works, but surely cannot be the best way to do it, right?
Here is a db<>fiddle with the example table and the statements above.
val->>0.val->>0returnedNULLfor all my rows.jsonb, in mine it'sjson. Your approach only seems to work withjsonb, whereas the one below for both: dbfiddle.uk/… I'll update my answer to incorporate that info. Thanks!