2016-04-25 4 views
1

Gibt es in AWS Redshift eine Möglichkeit, alle Schlüssel/Wert-Paare aus einer JSON-Zeichenfolge abzufragen, bei der jeder Datensatz eine andere Anzahl von Schlüssel/Wert-Paaren aufweist?Abfrage von variierenden JSON-Zeichenfolgen in AWS Redshift

I.e. Im folgenden Beispiel hat das erste Tier das Attribut "location", das zweite dagegen nicht. Mit Hilfe der json_extract_path_text Funktion I Attribute auswählen kann ich für beide Aufzeichnungen wissen existieren, aber wenn sich die Position abzufragen versuchen, wird es scheitern:

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"

Gewünschtes Ergebnis:

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

extra ',' nach Standort –

+0

@vkp Entschuldigung ja aktualisierte Abfrage. Auch ohne das nachgestellte Komma bekomme ich dieselbe Fehlermeldung – fez

Antwort

0

gefunden, dass dieser json_extract_path_text arbeitet mit :

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;