Is there a way in AWS Redshift to query all key/value pairs from a JSON string where each record has a different number of key/value pairs?
AWS Redshift中是否有一种方法可以从JSON字符串中查询所有键/值对,其中每个记录具有不同数量的键/值对?
I.e. in the below example, the first animal has the 'location' attribute whereas the second does not. Using the json_extract_path_text
function I can pick out attributes I know exist for both records but when trying to query the location it will fail:
即在下面的例子中,第一只动物具有“位置”属性而第二只动物没有。使用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;
ERROR: 42601: syntax error at or near "location"
错误:42601:“位置”或附近的语法错误
Desired Outcome:
期望的结果:
animal_id name animal_type age location
1 harry cat 2 oakland
2 louie dog 4 NULL
1 个解决方案
#1
0
Found that that json_extract_path_text works with ISNULL
:
发现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;
#1
0
Found that that json_extract_path_text works with ISNULL
:
发现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;