Reputation: 1835
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?
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:
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"
Desired Outcome:
animal_id name animal_type age location
1 harry cat 2 oakland
2 louie dog 4 NULL
Upvotes: 1
Views: 862
Reputation: 1835
Found that that json_extract_path_text works with 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;
Upvotes: 0