【问题标题】:How to parse retrieve value from a json string field in Redshift/SQL如何从 Redshift/SQL 中的 json 字符串字段中解析检索值
【发布时间】:2020-11-20 12:56:27
【问题描述】:

我有一行看起来像这样:


标识 | json_list |预期结果

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

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


我想根据 id 列检索“文本”字段。如何在 AWS Redshift 中实现这一目标?我知道 Redshift 有一些 json 函数,它需要与某种循环条件配对,但我不确定在 SQL 中是否可行

【问题讨论】:

    标签: sql json amazon-redshift


    【解决方案1】:

    请告诉我,我是否正确理解了您的问题。 因为数据有点混乱。

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

    解决方案 ->

    第 1 步 - 遍历各种 JSON 元素

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

    第 2 步 - 解析特定 JSON 元素中的键、值对

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

    所以,假设我有一张桌子 -

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

    插入数据 -

    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')
    

    数据长什么样子-

    这就是查询的方式-

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

    结果 -

    但是,将 JSON 存储在 Redshift 中并不是一个好习惯。

    关于原因的文档 - Link

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多