I need to post some objects to a flask app where, with each object made of 2 key-value pairs.
I'm using postman to test sending 1 object as json, but I need the ability to send multiple objects ( again each of which are made of 2 kv pairs as in screenshot )
My flask app looks like:
json = request.get_json(force=True) # receives request from postman
for j in json:
print str(j)
test = [{'a': j['key1'], 'token':j['key2']} for j in json ]
I would like rebuild the json into a list ('test') of dictionaries with dic containing 2 kv pairs (i.e. each dic is an object).
Unfortunately I realized that because json above is
{u'key2': u'xyz', u'key1': u'abc'}
I'm getting:
TypeError: string indices must be integers
In this case there is only 1 object, but How can I iterate through the json variable to build the list of dics I need?
解决方案
I was just looking for a way to make the code a little more fault tolerant and able to handle both single and multiple objects
The easy way to do that is to check the type of data coming in and change it into a standardized form that the rest of your code can consume. If you get a dict just create a list to hold the dict and the rest of the code will work.
json = request.get_json(force=True) # receives request from postman
for j in json:
print str(j)
if isinstance(json, dict):
json = [json]
test = [{'a': j['key1'], 'token':j['key2']} for j in json ]