H2 does not have JSON extraction functions like JSON_VALUE(my_json, '$.myFieldName')
(e.g. MySQL). However, the H2 Grammar reference for "field reference" states:
( expression ) . fieldName
Returns field value from the row value or JSON value. Returns NULL if value is null or field with specified name isn't found in JSON. Expression on the left must be enclosed in parentheses if it is an identifier (column name), in other cases they aren't required.
(My emphasis)
create table my_table (
id int generated by default as identity,
my_json JSON null default null,
);
insert into my_table (my_json) values ('{ "myFieldName": "foo bar" }');
select id, my_json, (my_json).myFieldName as baz from my_table;
NULL
values returned for the baz
alias - all others are as expected. I do not get any error with this syntax. However, I also do not get the wanted result foo bar.Can this be used as I am intending (to extract a field from a JSON object), and am I using this correctly? If not, how should I use it?
The question JSON_VALUE usage in H2 database grapples with the same sort of problem; an answerer has suggested either
I do not want to go through the complexity to create custom functions and import 3rd party libraries since this database is used only for local development (project team's decision...), while a proper DB engine of another dialect is used when deployed, so not looking at (1).
I have been able to use some adaptation of the regular expression method together with REGEXP_SUBSTR()
, but this leaves clumsy code (regular expressions are involved after all), and I am wondering about simpler alternatives. It does look suspicious to me that H2 provides functions to create JSON objects and arrays, but not use them also (apart from the above, as far as I can tell).
insert into my_table (my_json) values (JSON '{ "myFieldName": "foo bar" }');
Attempt to insert a character string literal into JSON column in H2 creates a JSON string value.
select id, my_json, (my_json)."myFieldName" as baz from my_table;
Unquoted identifiers are converted by default to the upper case.