PLPGSQL returned array, how to parse in Python?
I'm getting an array from plpgsql that looks like this:
[0:2]={
"(ab023500-ceef-41d6-af33-635964dbffde,Koen,\"\",Schmeets,{koen@heizoo.com},31631205427},\"{\"\"Test categorie\"\"}\",{ff0000})",
"(384cb1e9-58b9-4bdf-9da6-eb3d9355471b,Marc,\"\",Vrijhof,{},{},\"{\"\"Test categorie\"\"}\",{ff0000})",
"(9c19ec5c-6b95-456a-af6f-c3388835b780,Michael,\"\",\"Baas ;)\",{},{}, \"{\"\"Subcategorie test\"\",\"\"Test categorie\"\"}\",\"{NULL,ff0000}\")"}
I have built my own interpreter to get the array in a list of Python,开发者_开发问答 but it doesn't seem to be fail-proof. Does anybody have a clue how to parse this array in Python?
Edit
unnest()
made it possible for me to get a nice array with the following function:
CREATE FUNCTION array_to_json_string(in_varchararray character varying[])
RETURNS character varying LANGUAGE plpythonu AS
$_$
import cjson
plan = plpy.prepare("SELECT * FROM unnest($1)", ["varchar[]"])
rv = plpy.execute(plan, [in_varchararray])
retList = []
for r in rv:
retList .append(r["unnest"])
return cjson.encode(retList)
$_$;
Although... it is pretty slow!
Does anybody know how to turn the plpgsql array into comma separated values?
Consider unnesting the array before it gets to python, either using unnest in 8.4 or roll your own with:
create or replace function unnest(anyarray) returns setof anyelement as $$
select $1[i] from generate_series(array_lower($1,1), array_upper($1,1)) i;
$$ language'sql' immutable;
Use array_to_string()
to convert an array into a comma separated string.
Like this:
SELECT array_to_string(
$$[0:2]={
"(ab023500-ceef-41d6-af33-635964dbffde,Koen,\"\",Schmeets,{koen@heizoo.com},{31631205427},\"{\"\"Test categorie\"\"}\",{ff0000})",
"(384cb1e9-58b9-4bdf-9da6-eb3d9355471b,Marc,\"\",Vrijhof,{},{},\"{\"\"Test categorie\"\"}\",{ff0000})",
"(9c19ec5c-6b95-456a-af6f-c3388835b780,Michael,\"\",\"Baas ;)\",{},{},\"{\"\"Subcategorie test\"\",\"\"Test categorie\"\"}\",\"{NULL,ff0000}\")"
}$$::text[]
, ',');
精彩评论