2016-03-23 13 views
8

Ho un array json memorizzato nel mio database postgres. JSON simile a questa:Come trasformare un array json in righe in postgres

[ 
     { 
      "operation": "U", 
      "taxCode": "1000", 
      "description": "iva description", 
      "tax": "12" 
     }, 
     { 
      "operation": "U", 
      "taxCode": "1001", 
      "description": "iva description", 
      "tax": "12" 
     }, 
     { 
      "operation": "U", 
      "taxCode": "1002", 
      "description": "iva description", 
      "tax": "12" 
     } 
    ] 

ora ho bisogno di selezionare l'array in modo che ogni elemento è in una diversa riga del risultato della query. Quindi l'istruzione SELECT effettuo deve restituire i dati in questo modo:

data 
-------------------------------------------------------------------------------------- 
{ "operation": "U", "taxCode": "1000", "description": "iva description", "tax":"12"} 
{ "operation": "U", "taxCode": "1001", "description": "iva description", "tax":"12"} 
{ "operation": "U", "taxCode": "1002", "description": "iva description", "tax":"12"} 

Ho provato ad utilizzare la funzione

SELECT unnest(json_data::json) 
FROM my_table 

unnest() ma non accetta il tipo jsonb

+2

'unnest()' è per i tipi di array di PostgreSQL. [Uso] (http://www.postgresql.org/docs/current/static/functions-json.html) 'json_array_elements (json)' (9.3+), 'jsonb_array_elements (jsonb)' (9.4+) o 'json [b] _array_elements_text (json [b]) '(9.4+) – pozs

+0

Grazie. Se rispondi alla domanda, posso accettarlo. – k4ppa

risposta

10

Inserisco la risposta originariamente scritta da poz nella sezione commenti.

unnest() è per i tipi di array di PostgreSQL.

Invece una delle seguenti funzioni possono essere utilizzati:

  • json_array_elements(json) (9.3+)
  • jsonb_array_elements(jsonb) (9.4+)
  • json[b]_array_elements_text(json[b]) (9.4+)

Esempio :

select * from json_array_elements('[1,true, [2,false]]') 

valore di uscita

------------- 
| 1   | 
------------- 
| true  | 
------------- 
| [2,false] | 
------------- 

Here in cui la documentazione per v9.4 può essere trovato.

6

Vorrei suggerire usando il comando json_to_recordset nel tuo caso. SQL dovrebbe quindi essere:

select * from json_to_recordset('[{"operation":"U","taxCode":1000},{"operation":"U","taxCode":10001}]') as x("operation" text, "taxCode" int); 

Il risultato è:

------------------------ 
| |operation|taxCode | 
------------------------ 
| 1 | "U" | 1000 | 
------------------------ 
| 2 | "U" | 10001 | 
------------------------ 

Le colonne (o chiavi JSON) dell'esempio possono essere liberamente ulteriormente ampliate.

+0

Grazie, non sono riuscito a creare un tavolo così bello. – user2080851

Problemi correlati