Zum Hauptinhalt wechseln

How to extract property from JSON Array

I have to extract single property from JSON Array - there are many ways.

A small sample function with two variants:

create or replace function get_property_from_array(
    p_json      in json_object_t default null, 
    p_property  in varchar2,
    p_occurance in number default 0
) return varchar2
is
    l_json_array    json_array_t := json_array_t();
    l_json          json_object_t := json_object_t();
    l_clob          clob;
    l_result        varchar2(200 char);
begin

    l_json := coalesce(p_json, new json_object_t('{
                            "d": {
                                "results": [
                                    {
                                        "myProperty": "TEST-1"
                                    },{
                                        "myProperty": "TEST-2"
                                    }
                                ]
                            }
                        }')
                        );

    l_clob := l_json.to_clob();

    --Variante 1
    l_json_array    := l_json.get_object('d').get_array('results');
    l_json          := treat(l_json_array.get(p_occurance) as json_object_t);
    l_result        := l_json.get_string(p_property); 

    return l_result;

    --Variante 2 *OUTDATED*
    --Stop Writing JSON_TABLE SQL Manually -> https://haniel.hashnode.dev/stop-writing-jsontable-sql-manually-joelkallmanday
    for r_row in (
        select
            my_property
        from json_table (
            l_clob format json,
            '$.d.results[*]' columns (
                my_property varchar2 (4000) path '$."myProperty"'
            )
        )
        where rownum - 1  = p_occurance
    )
    loop
        l_result    := r_row.my_property;
    end loop;

end get_property_from_array;

 

Kommentare

Noch keine Kommentare zu diesem Beitrag.