In our database, one JSONB column contains an object which has a property which is a string encoded JSON object. I need to deserialize this string during the query and inspect its values.
create table datas (id int, data jsonb);
insert into datas (id, data) values (1, '{"key1": "{\"foo\": \"bar\"}"}');
I can select the string value, but then casting that into a JSONB object doesn't work. These queries all return null for the foo
.
select data->'key1'->'foo' from datas;
select to_json(data->'key1')->'foo' from datas;
select (data->'key1')::jsonb->'foo' from datas;
dbfiddle: https://dbfiddle.uk/?rdbms=postgres_9.6&fiddle=9c0a9f7f1323a35051daba5177e52f57
'{"key1": "{\"foo\": \"bar\"}"}'
is "wrong". I guess it should be:'{"key1": {"foo": "bar"}}'
'{"key1": "{\"foo\": \"bar\"}"}'
the value ofkey1
is a single string, not a JSON structure. That's whydata->'key1'->'foo'
doesn't work. As you seem to expect the value ofkey1
to be a nestedJSON
you have to get rid of the additional double quotes.'{"key1": {"foo": "bar"}}'
-> 'key1' -> 'foo'` will work as expected. Your value'{"key1": "{\"foo\": \"bar\"}"}'
is essentially the same structure as'{"key1": "some string with the words foo and bar"}'