Skip to content
Advertisement

Postgresql, retrieve value for specific key from json array

I have Postgres JSONB array of objects, looking like this :

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.

Advertisement

Answer

In Postgres 9.4+ use the function jsonb_array_elements() in a lateral join:

You can implement the idea in a simple function, e.g:

In Postgres 12+ you have a nice alternative in the form of jsonb path functions:

Db<>Fiddle.

Read more about JSON Functions and Operators.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement