【问题标题】:Querying varying JSON strings in AWS Redshift在 AWS Redshift 中查询不同的 JSON 字符串
【发布时间】:2016-04-25 15:29:20
【问题描述】:

AWS Redshift 中是否有一种方法可以从 JSON 字符串中查询所有键/值对,其中每条记录具有不同数量的键/值对?

即在下面的示例中,第一个动物具有“位置”属性,而第二个没有。使用json_extract_path_text 函数,我可以挑选出我知道两条记录都存在的属性,但是在尝试查询位置时它将失败:

   create table test.jsondata(json varchar(65000));
    insert into  test.jsondata(json) values ('{ "animal_id": 1, "name": "harry", "animal_type": "cat", "age": 2, "location": "oakland"}');
    insert into  test.jsondata(json) values ('{ "animal_id": 2, "name": "louie","animal_type": "dog", "age": 4}');

    select 
      json_extract_path_text(JSON,'animal_id') animal_id,
      json_extract_path_text(JSON,'name') name,
      json_extract_path_text(JSON,'animal_type') animal_type,
      json_extract_path_text(JSON,'age') age,
      json_extract_path_text(JSON,'location') location
    from test.jsondata
    order by animal_id;

错误:42601:“位置”或附近的语法错误

期望的结果:

animal_id name animal_type age location
1 harry cat 2 oakland
2 louie dog 4 NULL

【问题讨论】:

  • 定位后的额外,
  • @vkp 抱歉,更新了查询。即使没有尾随逗号,我也会收到相同的错误消息

标签: sql json amazon-web-services amazon-redshift


【解决方案1】:

发现 json_extract_path_text 与 ISNULL 一起使用:

select 
      json_extract_path_text(JSON,'animal_id') animal_id,
      json_extract_path_text(JSON,'name') name,
      json_extract_path_text(JSON,'animal_type') animal_type,
      json_extract_path_text(JSON,'age') age,
      ISNULL(json_extract_path_text(JSON,'location'),NULL) location
    from test.jsondata
    order by animal_id; 

【讨论】:

    猜你喜欢
    • 2016-09-12
    • 1970-01-01
    • 2014-12-24
    • 1970-01-01
    • 2020-10-12
    • 2019-02-17
    • 2017-01-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多