jsonpostgresqlpsycopg2simplejson

psycopg2 postgres sql request of sum and count returns format which is not respecting json.dump


I have the following query:

import psycopg2
import simplejson as json


payload = {
   "type": type,
   "creators": None,
   "type_count": None,
   "total_monitary_action_count": None
  }

cur.execute('''
      SELECT SUM(currentmonitaryactioncount) as totalmonitaryactioncount , COUNT(*) as totalnumberofcreators
      FROM users_contentcreatorusers
      WHERE approvedcreator = true AND ''' + str(type) + ''' = true
      ''')

then

 record = cur.fetchall()
 record = json.dumps(record)
 print('here is the record dump thing')
 print(record)
 payload["total_monitary_action_count"] = record[0]
 payload["type_count"] = record[1]

the print out

here is the record dump thing
[[102923243, 2043]]

here is the result of my

payload["total_monitary_action_count"] = record[0]
payload["type_count"] = record[1]

'type_count': '[', 'total_monitary_action_count': '['}

now i see the double []and i attempted record[0][0] with no positive effect.

What am I doing wrong.


Solution

  • Since the result is a list with a list, you should retrieve the data as

    payload["total_monitary_action_count"] = record[0][0]
    payload["type_count"] = record[0][1]
    

    and remove the following line which is going to serializes the result, that in this case I don't see why it is needed.

    record = json.dumps(record)