I am using the http extension in Postgresql, making a request, and getting a list of jsonb [{keys, values}] in a single column details as a response.
It seems like there should be an easy way to create a new table from the keys and values.
Here is the request:
WITH sport_markets_api AS (
SELECT ((CONTENT::jsonb ->> 'data')::jsonb ->> 'sportMarkets')::jsonb AS details
FROM http_post(
'https://api.thegraph.com/subgraphs/name/',
'{"query": "{sportMarkets(first:2,skip:0,orderBy:timestamp,orderDirection:desc){id,timestamp,address,gameId,maturityDate,tags,isOpen,isResolved,isCanceled,finalResult,homeTeam,awayTeam }}"}'::text,
'application/json'))
I tried:
SELECT col.*
FROM sport_markets_api,
jsonb_to_recordset(details) AS col(id TEXT,tags TEXT,total INT)
and this works...however I am looking for an easier way to create columns from jsonb_object_keys(). It can be rather tedious when calling different APIs with > 10 columns.
Example response:
{"data":
{"sportMarkets":
[ {"id": "9f4a2", "tags": ["9006"], "total": null, "betType": "10001", "awayOdds": "203707333464004703", "awayTeam": "Ottawa Senators", "drawOdds": "0", "homeOdds": "796292666535995296", "homeTeam": "Los Angeles Kings", "isPaused": false},
{"id": "9f4a3", "tags": ["9007","9005"], "total": null, "betType": "10002", "awayOdds": "'||(random()*203707333464004703)::bigint||'", "awayTeam": "Nebraska Governors", "drawOdds": "0", "homeOdds": "'||(random()*796292666535995296)::bigint||'", "homeTeam": "Los Santos Bloods", "isPaused": true},
{"id": "9f4a2", "tags": ["9006"], "total": 5, "betType": "10003", "awayOdds": "'||(random()*203707333464004703)::bigint||'", "awayTeam": "Utah Saints", "drawOdds": "0", "homeOdds": "'||(random()*796292666535995296)::bigint||'", "homeTeam": "Burger King Sodas", "isPaused": false}
]
}
}
If you want to avoid specifying field types and names in your records when calling
jsonb_to_recordset(), before you pass that tocreate table as, then there's alsojsonb_populate_recordset()in case you have that structure already defined somewhere, astableor atype: demoIn case you don't already have a table or a type to map those to, you can avoid mapping out each
jsonindividually, by hand: list pairs of field names and values withjsonb_each_text(), then pivot that withcrosstab, kind of like here: