if I have
create table t1( attr text primary key, val text );
insert into t1 values( 'attr1', 'val1' );
insert into t1 values( 'attr2', 'val3' );
insert into t1 values( 'attr3', 'val3' );
would like to select to return one row
attr1=>val1, attr2=>val2, attr3=>val3
right now doing conversion in javascript, but would be nice for pg to return the row itself
Answer
based on @mu’s answer, the query:
select replace( replace( replace( array_agg( hstore( attr, val ) )::text
'"\"', '"'),
'\""', '"'),
'\"=>\"', '":"') from t1;
results in:
{"attr1":"val1","attr2":val2","attr3":"val3"}
which is quite nice JSON (as long as no quotes in values)
If you have hstore installed then you could use
array_agg:That would give you exactly the output you’re looking for. Of course, whatever interface you’re using would have to understand hstore and arrays or you’d have to unpack the results yourself; and if that was the case, it would probably be simpler to iterate over a simple
select attr, val from t1query and build the data structure in JavaScript.