如何将 Postgres 数据拆分为 JSON/object,或一种易于使用的 Express 格式

How to split up Postgres data into JSON/object, or an easily usable format for Express

我正在使用 pg-promise 来促进 Express 和 Postgres 数据库之间的请求。

使用 pg-promise 的 any:

db.any('select * from blog')
  .then(function (data) {
    console.log(data);
  })
  .catch(function (error) {
    console.log('ERROR:', error);
  });

Postgres 中只有一行 table,所以上面的查询从 Postgres 中获取了一个数据块,当输出到终端时,它看起来像这样:

[ { id: 1,
    date: '2018-12-17',
    title: 'Here is a Title',
    article: "Okay, there's not much here yet.",
    img1: null,
    img2: null,
    img3: null,
    keywords: 'news' } ]

为了将这些数据分解成可用的位,然后我可以将这些位分配给 Express 中的值,我尝试对此数据使用 JSON.parse()。我真的不知道这样做会带来什么。

db.any('select * from blog')
  .then(function (data) {
    data = JSON.parse(data); // attempting to parse the Postgres data
    console.log(data);
  })

发生错误:

ERROR: SyntaxError: Unexpected token o in JSON at position 1

我也试过像调用对象一样调用这个数据。

db.any('select * from blog')
  .then(function (data) {
    console.log(data);
    console.log(data.id); // attempting to get just the id from the data
  })

输出到终端为:

undefined

如何在 Express 等 js 环境中使用这些数据?不确定它是否有所作为,但我正在尝试使用 Pug 将所有内容模板化到前端。

尝试 JSON.parse(JSON.stringify(数据));

select 查询 returns 对象数组,数组中的每个元素对应于 table (博客)中的一行,在你的情况下,对象中的每个键对应到 table 列。

我不确定你为什么要 JSON 解析它,因为 JSON 需要一个对象,它不能解析数组。