[postgresql] pl/sql json, jsonb를 이용한 배열 map사용

easywoo8080·2024년 12월 2일

PostgreSQL

목록 보기
1/3
-- DROP FUNCTION "practice".test();

CREATE OR REPLACE FUNCTION "practice".test()
	RETURNS int4
	LANGUAGE plpgsql
AS $function$
	DECLARE
	json_array json[] := ARRAY[]::json[];
    json_data json := '{}'::jsonb;

	
    name text;
    city text;
	age numeric;
	test numeric;

	updateCity text;

	BEGIN
	RAISE NOTICE 'BEGIN -------------------------------------------------------: ';

	json_data := jsonb_set(json_data::jsonb, '{name}', '"David"'::jsonb)::json;
	json_data := jsonb_set(json_data::jsonb, '{age}', '21'::jsonb)::json;
	json_data := jsonb_set(json_data::jsonb, '{city}', '"San Francisco"'::jsonb)::json;


	updateCity := 'busan';
	json_array := array_append(json_array, json_data);
	json_data := jsonb_set(json_data::jsonb, '{age}', '41'::jsonb)::json;
	json_data := jsonb_set(json_data::jsonb, '{city}', to_jsonb(updateCity))::json;
	
	RAISE NOTICE 'json_array updateCity: %', (json_array[1]::jsonb->>'city');
	json_array := array_append(json_array, json_data);
    FOR i IN 1..array_length(json_array, 1) LOOP
		/*데이터를 계산 또는 조작하려면 꼭 변숫에 저장해야함 ->>로 바로 호출해서 사용 불가능
        2024-11-28 :: ->>로 조작 가능 단 항상 형변환을 해야 함:: ->>로 조작 가능 단 항상 형변환을 해야 함*/
        
		name := json_array[i]->> 'name';
		age := json_array[i]->> 'age';
		city := json_array[i]->> 'city';


        RAISE NOTICE 'name %:', name;
        RAISE NOTICE 'age %:', age;
        RAISE NOTICE 'city %:', city;
        RAISE NOTICE 'Element %: %', i, json_array[i];
    END LOOP;
    
--    RAISE NOTICE 'Updated JSON: %', json_data;
	return 1;
	END;
$function$
;

Output

BEGIN -------------------------------------------------------:
json_array updateCity: San Francisco
name David:
age 21:
city San Francisco:
Element 1: {"age": 21, "city": "San Francisco", "name": "David"}
name David:
age 41:
city busan:
Element 2: {"age": 41, "city": "busan", "name": "David"}

0개의 댓글