解析 Postgresql 对象数组的最佳方法?

The best way to parse array of objects Postgresql?

我得到了结果:

tools: '{"(2,adobe-xd,\"Adobe XD\")","(42,wordpress,Wordpress)"}',
images: '{"(18,,)", "(19,heel,\"\")"}'

来自 typeorm 查询函数:

select
...
coalesce(array_agg(distinct row(tools.id, tools.value, tools.name)) filter (where tools.id is not null), '{}') as tools,
coalesce(array_agg(distinct row(images.id, images.title, images.description)) filter (where images.id is not null), '{}') as images
from project 
LEFT JOIN "project_tools_tool" "project_tools" ON "project_tools"."projectId"="project"."id" 
LEFT JOIN "tool" "tools" ON "tools"."id"="project_tools"."toolId"  
LEFT JOIN "project_image" "images" ON "images"."project_id"="project"."id"
where project.id in (select project.id from project order by project.order desc offset 3 limit 4)
group by project.id
order by project.order desc

我想将 toolsimages 解析为普通对象数组,例如:

tools: [
  {
    id: 2,
    value: 'adobe-xd',
    name: 'Adobe XD'
  }, {
    id: 42,
    value: 'wordpress',
    name: 'Wordpress'
  }
],
images: [
  {
    id: 18,
    title: null,
    description: null
  }, {
    id: 19,
    title: 'heel',
    description: ''
  }
]

最好的解析方法是什么?是否可以在 postgresql 查询中解析它?

这是一个使用正则表达式的解决方案,可能有现有的库可以做到这一点,但如果您想自己动手做:

const tools = '{"(2,adobe-xd,\"Adobe XD\")","(42,wordpress,Wordpress)"}';
const images = '{"(18,,)", "(19,heel,\"\")"}';

const parsePostgresqlObject = str => {
  return JSON.parse(str.replace(/^{/, '[').replace(/}$/, ']')).map(chunk => {
    const [_, ...matches] = chunk.match(/^\((.*?),(.*?),(.*)\)$/);
    const [id, title, description] = matches.map(e => {
      if(!e) return null;
      try {
        return JSON.parse(e);
      } catch(ex) {
        return e;
      }
    });
    return { id, title, description };
  });
};

console.log(parsePostgresqlObject(tools));
console.log(parsePostgresqlObject(images));