2

I have a database table(call it table) with jsonb column(lets say column). Column contains bellow data:

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

Now I want to create view for this table with fields in snake_case format, so it should looks like:

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

My latest query looks like this:

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;

How to transform data from inside of profileGroups array?

Example at DB Fiddle

1
  • You have invalid JSON ! Can you fix it Commented Dec 22, 2023 at 13:30

1 Answer 1

2

If the elements which you want convert are already known then we can use a bunch of nested replace() statements :

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.