I have this sample data:
ID Name
1 {'a':'content1'}
1 {'b':'content1'}
1 {'c':'content2'}
1 {'d':'content2'}
1 {'e':'content3'}
1 {'f':'content3'}
2 ['content4']
2 ['content4']
2 ['content5']
2 ['content5']
with
ID : INT
Name : JSON
I want to have this result
ID Name
1 content1
1 content1
1 content2
1 content2
1 content3
1 content3
2 content4
2 content4
2 content5
2 content5
Usually, when dealing with JSON
, I always use ::JSON ->> 'key'
but, when ID
= 1 then key
of name column change greatly. So I wonder if there is any way to get value (content) without specificly call the key of JSON values.
I literally dont know how to solve this problem to provide my try.
p/s: postgreSQL only please
VERSION: PostgreSQL 11.4 (Debian 11.4-1.pgdg90+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 6.3.0-18+deb9u1) 6.3.0 20170516, 64-bit
2
Answers
You can use
json_typeof()
to determine what to use in a lateral join to eitherjson_each_text()
forobject
values orjson_array_elements_text()
forarray
values and thenunion
the results.If you need to deal with multiple keys/array elements, you can apply a limit clause when extracting the keys/elements.
Note that the
limit
will pick an arbitrary element, it’s not guaranteed that it’s the "first" one – but highly likely.To pick an element by index, you could use:
If your
name
column is defined asjson
(rather thanjsonb
which it should be), then you need to use the correspondingjson_xxx
function (notjsonb_xxx
)Online example