在 AWS Redshift 中查询不同的 JSON 字符串
Querying varying JSON strings in AWS Redshift
AWS Redshift 中是否有一种方法可以从 JSON 字符串中查询所有 key/value 对,其中每条记录都有不同数量的 key/value 对?
即在下面的示例中,第一只动物具有 'location' 属性,而第二只动物则没有。使用 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"
期望的结果:
animal_id name animal_type age location
1 harry cat 2 oakland
2 louie dog 4 NULL
发现 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;
AWS Redshift 中是否有一种方法可以从 JSON 字符串中查询所有 key/value 对,其中每条记录都有不同数量的 key/value 对?
即在下面的示例中,第一只动物具有 'location' 属性,而第二只动物则没有。使用 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"
期望的结果:
animal_id name animal_type age location
1 harry cat 2 oakland
2 louie dog 4 NULL
发现 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;