我的问题的答案:Detecting column changes in a postgres update trigger让我将数据库中的行转换为等效的hstore。它很聪明,但导致阵列列类型的序列化/反序列化问题。
我有一些数组类型的列,例如:
select hstore_to_json(hstore(documents.*)) from documents where id=283;
给我(缩写形式):
{"id": "283", "tags": "{potato,rutabaga}", "reply_parents": "{7}"}
我真正喜欢的是
"tags": ["potato", "rutabaga"], "reply_parents": [7]
因为这是格式良好的JSON。从技术上讲,第一个响应是也是格式良好的JSON,因为数组已经被字符串化并且被发送到了#34; {potato,rutabaga}"。这需要我摆弄我得到的答案的解析,虽然这不是世界末日,但如果事实证明是不必要的话,那就有点痛苦。
在行上调用row_to_json首先将数组类型转换为正确的json数组表示形式,但它似乎没有json对象上的set减法类型运算符(问题中的hstore - hstore)上面是我发送"这些列已经改变"事件在我的websocket线上)。因此,欢迎任何关于如何在数据库中正确工作的建议。 (或者通过数组的方式将字符串化为hstore,或者通过在json对象上进行set减法来实现)。
答案 0 :(得分:1)
如果找不到任何自然解决方案,您可以始终信任正则表达式。
create or replace function hj(json text)
returns text language plpgsql immutable
as $$
begin
return
regexp_replace(
regexp_replace(
regexp_replace(
json, '([^"{]+?),', '"\1", ', 'g'),
'([^"{ ]+?)}"', '"\1"]', 'g'),
'"{"', '["', 'g');
end $$;
select hj('{"id": "283", "tags": "{potato,rutabaga}", "reply_parents": "{7}"}');
-- gives:
-- {"id": "283", "tags": ["potato", "rutabaga"], "reply_parents": ["7"]}