简体   繁体   English

如何从 Redshift/SQL 中的 json 字符串字段解析检索值

[英]How to parse retrieve value from a json string field in Redshift/SQL

I have a row that looks like this:我有一排看起来像这样:


id |编号 | json_list | json_list | expected_result预期结果

"1" | "1" | [{"id":"1", "text":"text1"},{"id":"3", "text":"text3"}] | [{"id":"1", "text":"text1"},{"id":"3", "text":"text3"}] | "text1" “文本1”

"2" | "2" | [{"id":"2", "text":"text2"},{"id":"3", "text":"text3"}] | [{"id":"2", "text":"text2"},{"id":"3", "text":"text3"}] | "text2" “文本2”


I want to retrieve the "text" field based on the id column.我想根据 id 列检索“文本”字段。 How can I achieve that in AWS Redshift?如何在 AWS Redshift 中实现这一目标? I know Redshift has some json functions and it needs to be paired with some kind of loop condition, but I wasn't sure if it's possible in SQL我知道 Redshift 有一些 json 功能,它需要与某种循环条件配对,但我不确定它是否可能在 SQL

Please let me know, If I have understood your question correctly or not.请让我知道,如果我是否正确理解了您的问题。 Because the data is a bit confusing.因为数据有点混乱。

Id column value - 2 Your Json value - [{"id":"1", "text":"text1"},{"id":"3", "text":"text3"}] Expected Result - text1 Id 列值 - 2 您的 Json 值 - [{"id":"1", "text":"text1"},{"id":"3", "text":"text3"}]预期结果 - text1

Solution ->解决方案->

Step 1 - Iterating through various JSON Elements第 1 步- 遍历各种 JSON 元素

select json_extract_array_element_text('[{"id":"1", "text":"text1"},{"id":"3", "text":"text3"}]',1)

在此处输入图像描述

Step 2 - Parsing key,Value Pairs in a particular JSON Element第 2 步- 解析特定 JSON 元素中的键、值对

select json_extract_path_text(json_extract_array_element_text('[{"id":"1", "text":"text1"},{"id":"3", "text":"text3"}]',1),'text')

在此处输入图像描述

So, Suppose I have a table -所以,假设我有一张桌子 -

create table dev.gp_test1_20200731
(
id int,
json_list varchar(1000),
expected_result varchar(100)
)

Inserting Data -插入数据 -

insert into dev.gp_test1_20200731
values
(1,'[{"id":"1", "text":"text1"},{"id":"3", "text":"text3"}]', 'text1'),
(2,'[{"id":"2", "text":"text2"},{"id":"3", "text":"text3"}]', 'text2')

How does the data look like -数据如何 -

在此处输入图像描述

This is how the query would be -这就是查询的方式 -

select json_extract_path_text(json_extract_array_element_text(json_list,1),'text')
from dev.gp_test1_20200731
where id = 2

Result -结果 -

在此处输入图像描述

But, It is not a good practice of storing JSON's in Redshift.但是,将 JSON 存储在 Redshift 中并不是一个好习惯。

Documentation on why - Link关于原因的文档 - 链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM