python mailchimp api 2.0 json response error
Question: Hi I'm trying to set up a batch job taking data from the mysql database and
send those users to mailchimp to be used for direct email campaigns. I'm
having an issue with the my code running on python 2.6 Red Hat linux (Red Hat
4.4.7-4) and python 2.7.3 Debian 4.6.3-14. I know this code works on windows 7
python 2.7.2 anaconda ipython notebook but I get a mailchimp json response
error at the end I don't fully understand.

    
    
    import mysql.connector
    import mailchimp
    
    
    
    #prepare mysql connection
    def connection(query):
        cnx = mysql.connector.connect(user='x', password='x',
                                  host='x',
                                  port=xxxx,
                                  connection_timeout=60,
                                  database='database')
    
        cursor = cnx.cursor()
        cursor.execute(query)
        data=cursor.fetchall ()
        cursor.close()
        cnx.close()
        return data
    
    
    #execute query
    
    email_data=None
    query_con = ("SELECT * FROM email")
    email_data=connection(query_con)
    
    
    #set mailchimp api key
    apikey='key'
    
    
    #create mailchimp oauth instance
    m=mailchimp.Mailchimp(apikey)
    
    #set list id to target mailchimp list
    list_id='xxxx'
    
    #method to format table data to mailchimp structure
    def batch_load(data):
        b_load= [{"email":{"email":x[3]},"merge_vars":{"FNAME":x[1],"LNAME":x[2], "MMERGE3":x[0], 
                                                   "MMERGE4":x[6], "MMERGE5":x[7], "MMERGE6":x[8], "MMERGE7":x[10], "MMERGE8":x[11], 
                                                   "MMERGE9":x[12], "MMERGE10":x[13],"MMERGE11":x[14], "MMERGE12":x[16],
                                                   "MMERGE13":x[17]}} for x in data]
        return b_load
    
    
    #use method
    b_load=batch_load(email_data)
    #upload users to mailchimp with parameters: list_id, formated_data, no double op in, allow updates, do not update interests. 
    m.lists.batch_subscribe(list_id,b_load,False,True,False)
    

Here's a json upload sample:

    
    
    {
    'merge_vars': {
        'LNAME': u'Client',
        'MMERGE8': datetime.datetime(2014,
        6,
        20,
        7,
        33,
        43),
        'MMERGE9': 0,
        'FNAME': u'Dev',
        'MMERGE3': 74,
        'MMERGE6': 2,
        'MMERGE7': 99,
        'MMERGE4': u'(111)111-1111',
        'MMERGE5': u'90210',
        'MMERGE10': datetime.datetime(2015,
        3,
        9,
        14,
        4,
        50),
        'MMERGE11': None,
        'MMERGE12': None,
        'MMERGE13': 0
    },
    'email': {
        'email': u'dev@dev.com'
    }
    

}

Here's the error it seems like there's an issue with the date time format:

    
    
    File "/foo/bar/batch_job.py", line 113, in <module>
        m.lists.batch_subscribe(list_id,b_load,False,True,False)
    
      File "/usr/lib/python2.6/site-packages/mailchimp.py", line 1393, in batch_subscribe
        return self.master.call('lists/batch-subscribe', _params)
      File "/usr/lib/python2.6/site-packages/mailchimp.py", line 351, in call
        params = json.dumps(params)
      File "/usr/lib64/python2.6/site-packages/simplejson/__init__.py", line 370, in dumps
        return _default_encoder.encode(obj)
      File "/usr/lib64/python2.6/site-packages/simplejson/encoder.py", line 269, in encode
        chunks = self.iterencode(o, _one_shot=True)
      File "/usr/lib64/python2.6/site-packages/simplejson/encoder.py", line 348, in iterencode
        return _iterencode(o, 0)
      File "/usr/lib64/python2.6/site-packages/simplejson/encoder.py", line 246, in default
        raise TypeError(repr(o) + " is not JSON serializable")
    TypeError: datetime.datetime(2014, 6, 20, 7, 33, 43) is not JSON serializable
    

Any help is appreciated.

Thanks


Answer: This is actually a Python error, not a MailChimp error. the JSON module
doesn't know how to turn a datetime object into a JSON Value. You'll need to
convert it into a string yourself. MailChimp should be able to accept the
isoformat() string or, if you're working with a Date Merge Field (where time
isn't needed) you can call date().isoformat(). Here's some code that gets
converted into JSON properly:

    
    
    json.dumps({
        'merge_vars': {
            'LNAME': u'Client',
            'MMERGE8': datetime.datetime(2014, 6, 20, 7, 33, 43).date().isoformat(),
            'MMERGE9': 0,
            'FNAME': u'Dev',
            'MMERGE3': 74,
            'MMERGE6': 2,
            'MMERGE7': 99,
            'MMERGE4': u'(111)111-1111',
            'MMERGE5': u'90210',
            'MMERGE10': datetime.datetime(2015, 3, 9, 14, 4, 50).date().isoformat(),
            'MMERGE11': None,
            'MMERGE12': None,
            'MMERGE13': 0
        },
        'email': {
            'email': u'dev@dev.com'
        }
    })
    

You'll notice if you remove the `.date().isoformat()` from either `MMERGE8` or
`MMERGE10` that your error comes back.

