lets say i have a table like that
id name address Doc
1 {1:mark,2:john} {1:Home,2:Work,3:Club} {NI:299,Pass:A159}
2 {1:Max,2:Mo} {1:Home} {NI:300011}
what i want is to write a qurey to select a value from cell based on the key
for example
i want the value which has key = 2 in column named(Name) where id=1
so it should return
john
and so on.
so how can i do something like that without using substring?
3
Answers
Assuming you have a valid json values :
The query can be :
Demo here
If there are only key-value values in a non-valid JSON, then:
Demo here
If your data is as shown and isn’t JSON (or quoted) then you could use
regexp_substr()
to find the match, with a pattern that embeds the key value you want:Your script will need to supply the first
2
in the first line, and the1
in the third line; so more generically with bind variables:The pattern is looking for
{
or,
, followed by your key value, followed by a colon:
; and capturing everything up to another,
or}
. The other arguments are there to tell it to return the second capture group (the second2
in that line). The first group is the ‘or’ of({|,)
, and you want the second group(.*?)
which is the value for that pair.By varying the key value you get different results; with the same column and
1
:And you can use the same approach with the other key/value columns.
fiddle
Of course, it would be better to store the data relationally, not as key/value pairs within a string column.
Your
name
column is not valid JSON so you cannot use JSON functions.You could use regular expressions but they are slower than simple string functions. So, even though you said you do not want to use
SUBSTR
, you should useSUBSTR
:Which, for the sample data:
Outputs:
If you only want when
id = 1
then add that filter and if you want to make the index you are matching a more dynamic parameter then:Or use a parameterised query and a bind parameter (instead of a sub-query).
fiddle