Oracle
 SQL >> Datenbank >  >> RDS >> Oracle

Mit JSON in Oracle PL/SQL arbeiten

Vor 12c hatte PL/SQL keine native JSON-Unterstützung, und die pljson-Bibliothek füllt diese Lücke recht gut: https://github.com/pljson/pljson. Die Installation ist unkompliziert und die Beispiele sind solide.

Deklarieren Sie ein paar Variablen, um die geparste Struktur zu halten:

mapData json; results json_list; status json_value; firstResult json; geometry json; 

Navigieren Sie dann die Antwort als Objektgraph, statt mit String-Funktionen daran herumzupicken:

-- convert the result from the get to a json object, and show some results. mapData := json(v_ans); -- Show the status of the request status := mapData.get('status'); dbms_output.put_line('Status = ' || status.get_string()); IF (status.get_string() = 'OK') THEN results := json_list(mapData.get('results')); -- Grab the first item in the list resultObject := json(results.head); -- Show the human readable address dbms_output.put_line('Address = ' || resultObject.get('formatted_address').to_char() ); -- Show the json location data dbms_output.put_line('Location = ' || resultObject.get('geometry').to_char() ); END IF; 

Die Ausgabe liest sich so:

Status = OK Address = "St Paul, MN 55105, USA" Location = { "bounds" : { "northeast" : { "lat" : 44.9483849, "lng" : -93.1261959 }, "southwest" : { "lat" : 44.9223829, "lng" : -93.200307 } }, "location" : { "lat" : 44.9330076, "lng" : -93.16290629999999 }, "location_type" : "APPROXIMATE", "viewport" : { "northeast" : { "lat" : 44.9483849, "lng" : -93.1261959 }, "southwest" : { "lat" : 44.9223829, "lng" : -93.200307 } } } 

Auf 12.1.0.2 und neuer können Sie ganz auf die Bibliothek verzichten: JSON_VALUE, JSON_QUERY und JSON_TABLE übernehmen Extraktion und Abflachung nativ, und IS JSON validiert eine Spalte. Greifen Sie vor allem auf älteren Releases zu pljson oder wenn Sie Dokumente programmatisch aufbauen und verändern müssen.