Table Schema:
create table test_table
(
id serial not null,
data jsonb
);
Sample Data:
INSERT INTO public.test_table (id, data) VALUES (1, '[{"": "VALUE1", "KEY2": "VALUE2"}, {"KEY1": "VALUE3", "KEY3": "VALUE4"}]');
INSERT INTO public.test_table (id, data) VALUES (2, '[{"''KEY1 ''": "VALUE1", "KEY2": "VALUE2"}, {"KEY3": "VALUE3", "KEY4": "VALUE4"}]');
SQL Query:
SELECT id, arr_elem
FROM test_table AS tt, jsonb_array_elements(
(
SELECT data
FROM test_table
WHERE id = tt.id
)
) AS arr_elem
WHERE arr_elem#>'{KEY1}' IS NOT NULL
I would like to tune to above query to match the following scenarios:
- Find the keys with empty strings: Ex:
"": "VALUE1" - Find the keys with just single quotes: Ex:
"''": "VALUE1" - Find the keys with trailing spaces enclosed in single quotes: Ex:
"'KEY1 '": "VALUE1"
Tried to escape the quotes and spaces and the query didn't return the expected results.
UPDATE 1:
Solution for 1: http://sqlfiddle.com/#!17/6d431/20
SELECT id, arr_elem
FROM test_table AS tt, jsonb_array_elements(
(
SELECT data
FROM test_table
WHERE id = tt.id
)
) AS arr_elem
WHERE arr_elem->'' IS NOT NULL