在AWS Redshift中查询不同的JSON字符串

时间:2016-04-25 15:29:21

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

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

1 个答案:

答案 0 :(得分:0)

发现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;