PostgreSQL返回JSON对象作为键值对

时间:2019-03-25 13:06:51

标签: json postgresql jsonb

PostgreSQL实例以JSONB格式存储数据:

CREATE TABLE myschema.mytable (
    id   BIGSERIAL PRIMARY KEY,
    data JSONB     NOT NULL
)

数据数组可能包含以下对象:

{
  "observations": {
    "temperature": {
      "type": "float",
      "unit": "C",
      "value": "23.1"
    },
    "pressure": {
      "type": "float",
      "unit": "mbar",
      "value": "1011.3"
    }
  }
}

所选行应作为键值对返回,格式如下:

temperature,type,float,value,23.1,unit,C,pressure,type,float,value,1011.3,unit,mbar

以下查询至少返回每个对象,同时仍为JSON:

SELECT id, value FROM mytable JOIN jsonb_each_text(mytable.data->'observations') ON true;
1 | {"type": "float", "unit": "mbar", "value": 1140.5}
1 | {"type": "float", "unit": "C", "value": -0.9}
5 | {"type": "float", "unit": "mbar", "value": "1011.3"}
5 | {"type": "float", "unit": "C", "value": "23.1"}

但是结果是分开的并且不是文本格式。

如何返回data中所有对象的键值对?

1 个答案:

答案 0 :(得分:1)

这将拉平json结构,并有效地将值和顶级键名(例如温度和压力)连接起来,以达到预期的“深度”级别。看看这是否是您的初衷。

SELECT
    id,
    (
      SELECT STRING_AGG(conc, ',')
      FROM (
        SELECT CONCAT_WS(',', key, STRING_AGG(value, ',')) AS conc
        FROM (
          SELECT key, (jsonb_each_text(value)).value
          FROM jsonb_each(data->'observations')
        ) AS x
        GROUP BY key
      ) AS csv
    ) AS csv
FROM mytable

结果:

| id  | csv                                                 |
| --- | --------------------------------------------------- |
| 1   | pressure,float,mbar,1011.3,temperature,float,C,23.1 |
| 2   | pressure,bigint,unk,455,temperature,int,F,45        |

https://www.db-fiddle.com/f/ada5mtMgYn5acshi3WLR7S/0