I have a jsonb field attributes
in my table. It looks like this –
{
"id": "10",
"customer": [
{
"id": "001",
"name": "Customer1",
"customerType": "internal"
},
{
"id": "002",
"name": "Customer2",
"customerType": "external"
}
]
}
The customer array can have only 2 objects in it. I want to check if customer[0][‘customerType’] or customer[1][‘customerType’] is internal then i want a column as internal and have the name in it.
Similarly if customer[0][‘customerType’] or customer[1][‘customerType’] is external then i want a column as external and have the name in it.
I tried parsing the field but not sure if such conditional logic is doable using just SQL –
SELECT (attributes->'customer'->0->'name1') as internal
FROM table;
Any help is appreaciated.
2
Answers
You can use a JSON path query:
Use a path expression
Explanation
returns the array elements of internal customers.
You take the first one (index
0
)With
#>>
you extracts JSON sub-object at the specified path as text. Note that the path is casted astext[]