Skip to content
Advertisement

Insert json data into postgres table using python

We have a python script which pulls data form an API endpoint this way:

JavaScript

We got to this point and we do see the data in record_list, however we don’t know how to parse the data and insert it into a table.

We tried:

JavaScript

but it seems it is not a list, so what it is and how to import it into the DB?

The table has only 2 fields (currency_name and rate)

record_list sample:

JavaScript

Thanks!

Advertisement

Answer

Based on assumptions about what you are trying to achieve, an example:

JavaScript

record_list is a JSON object as string. Use json.loads to convert to Python dictionary. Then use psycopg2 to INSERT records. This is done using a parameterized query(insert_sql) which is executed in the for loop using the dictionary items() from the record_dict['rates]` dictionary. The transactions are the then committed to have the data persist to the table.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement