Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
555 views
in Technique[技术] by (71.8m points)

json - Split a varchar column in Redshift

I have a table sales with all the column has varchar as datatype.

 Name           items 
 Dave    {"item1": {"product": apple, "cost": 120}, "item2": {"product": orange, "cost": 80}}
 Nick      
 Jack    {"item1": {"product": melon, "cost": 100}, "item2": {"product": berries, "cost": 240}}

I goal is to split the column items as below using SELECT statement

Name    items1_product   items1_cost  items2_product  items2_cost 
 Dave        apple            120        orange           80     
 Nick     
 Jack        melon            100        berries         240

I tried to convert the datatype of items to Json by "select items::JSONB from sales " and I am getting error, type "jsonb" does not exist;

Is there any other way we can achieve this ?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Redshift doesn't have a native json datatype but it does have json parsing functions. What you have stored in the "items" column is text, not json. To extract an element from this json text you can use the Redshift json built-in functions which you can read about here - https://docs.aws.amazon.com/redshift/latest/dg/json-functions.html

So to extract item1's product name for each person you can:

select select json_extract_path_text(items, 'item1', 'product') as items1_product from <table>;

Now your json doesn't look to be properly formatted as word "apple" is a string value and should be quoted. I expect this was just an oversight in writing up the example for your question. If this isn't the case and you have some json cleanup to do there is a is_valid_json() function that you can use to ensure that your table json data is correct before trying to parse it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...