2017-01-19 10 views
1

Mit PostgreSQL 9.5.5 folgenden Beispiel jsonb Daten in einer Spalte Gegeben:PostgreSQL Schwierigkeit Extrahieren Feld aus jsonb Spalte

{ 
"item_id": "123456", 
"action_information_1": [ {"value": "259", "action_type": "read"} ], 
"action_information_2": [ {"value": "93", "action_type": "read"} ], 
"action_information_3": [ {"value": "53", "action_type": "read"} ], 
"action_information_4": [ {"value": "35", "action_type": "read"} ] 
} 

ich Schwierigkeiten programmatisch mit bin Extrahieren der ‚Wert‘ aus ‚action_information_1‘, das würde werden 259.

Es scheint, die Syntax von anderen Beispielen ist etwas anders als ich gesehen habe, hat die oben vorhergehenden ‚" ‚vor dem‘ [‘.

Jede Hilfe ist willkommen, danke

+1

Ihr Beispiel ist: der Schlüssel value

dies kann alternativ ein bisschen kürzer mit geschrieben werden ein ungültiges JSON-Dokument. Sie müssen '' 'um Schlüssel und Werte nicht' '' verwenden und das Array '[...]' darf nicht in Anführungszeichen stehen. –

+0

Bitte schauen Sie sich http://www.json.org/ –

+0

an 'col -> 'action_information_1' -> 0 - >> 'value'', wenn Sie den Array-Index parametrisiert haben' jsonb_extract_path (col ->' action_information_1 ',?) - >>' value'' – cske

Antwort

2

Wenn Sie die Syntaxfehler im JSON-Dokument die folgenden Werke zu beheben:

with test_data (doc) as (
    values (
    '{ 
    "item_id": "123456", 
    "action_information_1": [{"value": "259", "action_type": "read"}], 
    "action_information_2": [{"value": "93", "action_type": "read"}], 
    "action_information_3": [{"value": "53", "action_type": "read"}], 
    "action_information_4": [{"value": "35", "action_type": "read"}] 
    }'::json 
) 
) 
select doc -> 'action_information_1' -> 0 ->> 'value' 
from test_data 

doc -> 'action_information_1' bekommt das Array für diesen Schlüssel, der -> 0 kehrt das erste Array-Element und ->> 'value' dann wird der Wert, der zugeordnet ist

select doC#> '{action_information_1,0}' ->> 'value' 
from test_data 
Verwandte Themen