I'm trying to parse a JSON string into a table with it's value pairs.
Here is the JSON string:
{
"route": {
"coding": [
{
"code": "56",
"display": "ORAL",
"userSelected": true
}
]
}
}
My goal is to get it into a table like such:
| parent | key | value | type |
-------------------------------
| null | route | {coding: [...]} | object |
| route | coding | [{"code": "56", ...}] | array |
| route | coding | {"code": "56", ...} | object |
| coding | code | 56 | integer |
| coding | display | ORAL | text |
| coding | userselected | true | boolean |
I'm struggling with making a recursive call. I am able to either parse the array or the object, I just cannot figure out how to call one or the other based upon the type.
This is my current code:
WITH RECURSIVE temp (parent, key, value, type) AS (
SELECT parent, key, value, type
FROM t1
UNION ALL
SELECT parent, key, value, jsonb_typeof(value) AS type
FROM (
SELECT key AS parent, (jsonb_each(value)).*
FROM temp
WHERE temp.type = 'object') AS p1
), temp2 (parent, key, value, type) AS (
SELECT parent, key, value, type
FROM t1
UNION ALL
SELECT parent, key, jsonb_array_elements(value), 'object' AS type
FROM temp2
WHERE temp2.type = 'array'
)
SELECT parent, key, value, type FROM temp;
Any help is greatly appreciated. Thanks.