我有一个带有 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 数组内部转换数据?
如果你想要转换的元素是已知的,那么我们可以使用一堆嵌套的
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;