Search code examples
pythonpython-3.xpymysql

Insert array of arrays with pymysql and lambda


I have a lambda function which has the input of an array of arrays, I would like to store this array in full in a single mysql column.

I use pymysql to connect to the database, and it's added as a layer – so queries do work when legitimate.

The problem is I want to keep the array as something I can manipulate later, so I just want to stringify the whole array of arrays, and then later I will parse and break it down.

I am using Python 3.7. I would like to avoid non-core libraries as they would then need to be added to the lambda function and the AWS CDK script.


Solution

  • Convert that array to a JSON string:

    import json
    json_arr = json.dumps(arr)
    

    You can store it in a string-type column in MySQL but since MySQL 5.7.8 there is a special JSON data type that you could use: https://dev.mysql.com/doc/refman/8.0/en/json.html

    To convert JSON string back to array:

    arr = json.loads(json_arr)