如何在PostgreSQL中将JSON数组转换为行

时间:2019-09-26 21:02:54

标签: sql arrays json postgresql

我试图在有JSON类型列(来自SQL查询)的地方转换此结果

{
  "rows": [
    {
      "columns": {
        "jseq": 1,
        "Nombre": "0000956_LANZADOR",
        "rutaEsquema": "AXIS",
        "TipoDeComponente": "SQL",
        "value": 0,
        "detalleDelComponente": "Solución incidente 956"
      }
    },
    {
      "columns": {
        "jseq": 2,
        "Nombre": "0000956_02_Borrar_Mandatos.sql",
        "rutaEsquema": "AXIS",
        "TipoDeComponente": "SQL",
        "value": 1,
        "detalleDelComponente": "Brecha 67"
      }
    }
  ]
}

对此

Nombre                     | rutaEsquema | TipoDeComponente | detalleDelComponente
---------------------------+-------------+------------------+-----------------------
0000956_LANZADOR           | AXIS        | SQL              | Solución incidente 956
0000956_02_Borrar_Mandatos | AXIS        | SQL              | Brecha 67

我正在使用Postgresql

3 个答案:

答案 0 :(得分:0)

JSON processing functions中的

# even though this prints as two terms (which is kind of weird) print result[0].as_expr() #...this collapses it into one exec('poly_expr = '+str(result[0].as_expr())) print poly_expr #...which allows the expressions to be combined Poly(poly_expr, x) json_to_record正是这样做的。就您而言:

json_to_recordset

online demo

答案 1 :(得分:0)

SELECT r."Nombre",
       r."rutaEsquema",
       r."TipoDeComponente",
       r."detalleDelComponente"
FROM jsonb_to_recordset(/* your JSONB value */ -> 'rows') AS q(columns jsonb)
   CROSS JOIN LATERAL
      jsonb_to_record(columns)
         AS r(jseq bigint,
              "Nombre" text,
              "rutaEsquema" text,
              "TipoDeComponente" text,
              value bigint,
              "detalleDelComponente" text
             );

答案 2 :(得分:0)

一个选择是使用json_each函数将最外面的JSON对象扩展为一组键/值对,然后使用json_array_elements提取数组元素:

select elm->>'Nombre' as Nombre,
       elm->>'rutaEsquema' as rutaEsquema,
       elm->>'TipoDeComponente' as TipoDeComponente,
       elm->>'detalleDelComponente' as detalleDelComponente
  from
  (
   select elms -> 'columns' as elm 
     from(
          select json_array_elements(js.value) as elms
            from tab,
                 json_each(js_col) as js
         ) q1
  ) q2 

Demo