I found a way to store JSON data in a DB. Since I access the nodes from a remote service that returns a list nodes for each request, I need to build the correct json to store / retrieve from db.
Say API returned json text as: '{"cursor": null, "nodes" = [{"name": "Test1", "value: 1}, {"name": "Test2", "value: 2}, ...]}'
So, first we need to access the list of nodes as:
data = json.loads(api_data) nodes = data['nodes']
Now for the first record in the DB column we need to do the following:
str_data = json.dumps({"nodes": nodes})
So str_data will return a valid string / buffer, which we can save to the database using the "nodes" key.
For two or subsequent entries in the DB column, we will do the following:
# get data string from DB column and load into json db_data = json.loads(db_col_data) # get new/latest 'nodes' data from api as explained above # append this data to 'db_data' json as latest_data = db_data["nodes"] + new_api_nodes # now add this data back to column after json.dumps() db_col_data = json.dumps(latest_data) # add to DB col and DB commit
This is the right way to load / unload data from the database when adding / removing json and maintaining the proper format.
Thanks!
source share