Thursday, February 13, 2014

JSON and CSV

Yesterday I wrote a bit of Python to create new records in an application that exposed a JSON api. I decided to use csv files as input since that's the format that most of our customers use when exporting data. It's really well suited for creating json name=value pairs when using the python "request" libraries. The column headers are used as the names and the column values are used as, well, the values.

Code snippet:
mllc.py
167 def newCustomer(custInputFile):
168         print "adding Customers from " + custInputFile
169         with open(custInputFile, 'rb') as cfile:
170                 reader = csv.reader(cfile)
171                 rownum = 0
172                 for row in reader:
173                         #print row
174                         if rownum == 0:
175                                 header = row
176                         else:
177                                 colnum = 0
178                                 payload = {}
179                                 for col in row:
180                                         cname = header[colnum]
181                                         cval = col
182                                         payload[cname] = cval 
183                                         colnum += 1
184                                 Customersurl = url + '/customer/'
185                                 response = requests.post(Customersurl, data=json.dumps(payload), headers=headers) 
186                 
187                                 # Check for HTTP codes other than 201
188                                 if response.status_code != 201: 
189                                     print('Status:', response.status_code, 'Problem with the request. Exiting.')
190                                     exit()
191                         rownum = +1