PostgreSQL i JSON

PostgreSQL té un munt de funcions per a llegir camps en format JSON, les podeu trobar aquí.

Suposem una taula així:

idjson_array
1[0,”1234″,true]
2[1,”4567″

El select següent fallaria perquè en la posició 2 de json_array no existeix en el registre 2.

select json_array::jsonb->2 as is_true from taula_json

Per algun motiu, el registre 2 no s’ha enregistrat correctament. Ens cal poder verificar que tots els registres que volem seleccionar contenen un JSON vàlid. No he trobat cap funció a PostgrSQL que permeti saber-ho, així que he afegit aquesta funció d’usuari.

CREATE OR REPLACE FUNCTION public.is_json(p_json text)
RETURNS boolean
LANGUAGE plpgsql
IMMUTABLE AS
$function$
begin
return (p_json::json is not null);
exception
when others then
return false;
end;
$function$ ;

De manera que el select anterior el podem reescriure així:

select json_array::jsonb->2 as is_true from taula_json where is_json(json_array)