I have a json that I get as a file, I have loaded that in the Postgres database. Here is the json data:
{
"tablename": "test",
"columns": [
{
"name": "field1",
"datatype": "BigInt"
},
{
"name": "field2",
"datatype": "String"
}
]
}
Now I have to create a table dynamically, I am thinking of writing a function in Postgres to do that. So the table would be named test with 2 fields one as string and another as bigint.
I am able to get the table name by doing a select as below:
select (metadata->'tablename') from public.json_metadata;
However, I am having difficulty getting all the nested column names to form a create table statement.
1- How would you go about doing that, any built in Postgres functions to extract that.
2- Is a Postgres function the best way to approach this problem, or should I write this in python (I will have to learn Python) or shell script.
The number of columns would not be fixed, different json files will have different number of columns.
data_type
? Or was thatdatatype
or case sensitivedataType
orDATATYPE
or ..... ?? You get the picture. Bad Ideaselect 'create table ' || (metadata->'tablename') || '(' || (metadata->'columns'-> 0 -> 'name') || ' ' || (metadata->'columns'-> 0 -> 'datatype') || ', ' || (metadata->'columns'-> 1 -> 'name') || ' ' || (metadata->'columns'-> 1 -> 'datatype') || ');' from json_tables
Yeah, you should find solution to replace column index position since It can be n number of column and I couldn't find any.