Use json_object_keys() instead of extracting key:value pairs then only keeping .key field.
You can extract only the matching subexpression with regexp_substr() instead of matching the whole thing, then replacing it with the parenthesized part.
create table your_table(fixtures) as values
('{ "fixture_1":"fixture1"
,"fixture_2":"fixture2"
,"fixture_321":"fixture321"}');
select regexp_substr(json_object_keys(fixtures::json),'(d+)$')::int as "ID"
from your_table;
json_object_keys() is simpler and faster for the case than json_each_text(), Zegarek already provided that.
split_part() is simpler and faster for the case (always one_ as separator before the dangling number) than employing regular expressions. You seem to be asking for a solution without regexp: "without '.*?(d+)', '1')".
split_part(json_object_keys(fixtures::json), '_', 2)::int AS id
2
Answers
json_object_keys()
instead of extracting key:value pairs then only keeping.key
field.regexp_substr()
instead of matching the whole thing, then replacing it with the parenthesized part.$
matches the end of the input string.Demo at db<>fiddle:
json_object_keys()
is simpler and faster for the case thanjson_each_text()
, Zegarek already provided that.split_part()
is simpler and faster for the case (always one_
as separator before the dangling number) than employing regular expressions. You seem to be asking for a solution without regexp: "without'.*?(d+)', '1')
".See:
Also,
fixtures
should probably be typejson
orjsonb
to begin with, making the cast::json
unnecessary.You are aware that this produces a single set of from all top-level object keys, with possible duplicates? You may want to throw in
DISTINCT
:Or you may want IDs per row (no dupes per row if your key names are consistent):
fiddle
Related: