PLPGSQL返回数组,如何在Python中解析?

时间:2010-12-13 18:25:08

标签: python arrays parsing plpgsql plpython

我从plpgsql获取一个如下所示的数组:

[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}\")"}

我已经构建了自己的解释器以将数组放入Python列表中,但它似乎不是故障证明。 有没有人知道如何在Python中解析这个数组?

修改

unnest()使得我可以使用以下函数获得一个很好的数组:

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)
$_$;

虽然......很慢!

有人知道如何将plpgsql数组转换为逗号分隔值吗?

2 个答案:

答案 0 :(得分:0)

考虑在数组到达python之前取消它,或者使用8.4中的unnest或者使用自己的数据:

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;

答案 1 :(得分:0)

使用array_to_string()将数组转换为逗号分隔的字符串 像这样:

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[]
    , ',');