Reputation: 36317
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
please see TypeError: string indices must be integers with flask json
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?
Upvotes: 1
Views: 2344
Reputation: 77377
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 ]
Upvotes: 1
Reputation: 230
Let me de-construct your code assuming json
is a dictionary with the data {u'key2': u'xyz', u'key1': u'abc'}
test = [{'a': j['key1'], 'token':j['key2']} for j in json ]
What you were actually doing is iterating through the key in the dictionary and then treating the result as a dictionary, this will give you an error!
The j
in json
in each loop is the key, so in the first iteration you get the result 'key1'
and when you try j['key1']
you assumed that j
is a dictionary, but in fact it is a string, hence the error TypeError: string indices must be integers
.
This is probably what you are looking for to help you with your solution.
This will give you a list of dictionaries:
test = [{key, value} for key, value in json.items()]
The result:
[{u'key2': u'xyz'}, {u'key1': u'abc'}]
The reason your code failed is because you were trying to unnecessarily iterate through the dictionary, but if you wish to disassemble it simply do this:
[dict(a=json['key1'], token=json['key2'])]
Result:
[{'a': u'abc', 'token': u'xyz'}]
Upvotes: 1