问题
I have Postgres JSONB array of objects, looking like this :
'[
{
"skillId": "1",
"skillLevel": 42
},
{
"skillId": "2",
"skillLevel": 41
}
]'
This JSONB is a function argument.
What is the most efficient way to retrieve skillLevel
for skillId = "1"
.
I've tried to play with jsonb_array_elements
but everything I've done so far is looking really messy.
回答1:
with my_table(data) as (
values
('[
{
"skillId": "1",
"skillLevel": 42
},
{
"skillId": "2",
"skillLevel": 41
}
]'::jsonb)
)
select elem->>'skillLevel' as skill_level
from my_table
cross join jsonb_array_elements(data) elem
where elem->>'skillId' = '1';
skill_level
-------------
42
(1 row)
The above seems the simplest way, you can use the idea in a function, e.g.:
create or replace function extract_skill_level(data jsonb, id int)
returns integer language sql as $$
select (elem->>'skillLevel')::int
from jsonb_array_elements(data) elem
where elem->>'skillId' = id::text
$$;
select extract_skill_level
('[
{
"skillId": "1",
"skillLevel": 42
},
{
"skillId": "2",
"skillLevel": 41
}
]', 1);
来源:https://stackoverflow.com/questions/51212513/postgresql-retrieve-value-for-specific-key-from-json-array