如何将jsonb列数组中的元素转换为snake_case格式[PostgreSQL]

ttvkxqim  于 2024-01-07  发布在  PostgreSQL
关注(0)|答案(1)|浏览(154)

我有一个数据库表(叫它表)与jsonb列(让我们说列)。列包含以下数据:

{
  "country": "GB",
  "channel": "mobile",
  "profileGroups: [
    {
       "profiles": ["profileA", "profileB"],
       "negativeProfiles: ["negativeA"
    },{
       "profiles": ["profileC"],
       "negativeProfiles": null
    }
  ]
}

字符串
现在,我想为这个表创建一个视图,其中的字段是snake_case格式的,所以它看起来应该是这样的:

{
  "country": "GB",
  "channel": "mobile",
  "profile_groups: [
    {
       "profiles": ["profileA", "profileB"],
       "negative_profiles: ["negativeA"
    },{
       "profiles": ["profileC"],
       "negative_profiles": null
    }
  ]
}


我的最新查询看起来像这样:

CREATE OR REPLACE VIEW v_table
SELECT json_build_object(
'country', column_1 -> 'country',
'channel', column_1 -> 'channel',
'profile_groups', column_1 -> 'profileGroups'
)::jsonb as column_1
FROM table;


如何从profileGroups数组内部转换数据?
Example at DB Fiddle

eivgtgni

eivgtgni1#

如果你想要转换的元素已经知道了,那么我们可以使用一堆嵌套的replace()语句:

CREATE OR REPLACE VIEW v_table AS
SELECT REPLACE(REPLACE(column_1::TEXT, 'profileGroups', 'profile_groups'), 'negativeProfiles', 'negative_profiles')::jsonb AS column_1
FROM mytable;

字符串
Demo here

相关问题