Postgresql, retrieve value for specific key from json array

对着背影说爱祢 提交于 2019-12-19 07:50:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!