Reputation: 36347
I am testing a flask app where I need to post some key value pairs, but my flask app is expecting them in JSON format. At the command line I created json from my kv pairs like so:
>>> import json
>>> print json.dumps({'4': 5, '6': 7}, sort_keys=True,indent=4, separators=(',', ': '))
{
"4": 5,
"6": 7
}
when I put this into postman:
and post it to my app I get:
TypeError: string indices must be integers
However if I use:
[{
"4": 5,
"6": 7
}]
It works! Why is this happening?
Here is the app code. the error is happening at the last line:
json = request.get_json(force=True) # receives request from php
for j in json:
print str(j)
test = [{'ad': j['4'], 'token':j['6']} for j in json]
Upvotes: 0
Views: 2539
Reputation: 77407
You need to pass in a list
of dict
s because your code tries to process a list of dicts. The problem isn't related to json, that just happens to be how you read in the data structure. Here's your code as a single script demonstrating the problem. I changed the name to data
to avoid confusion with json
and I'm using repr
instead of str
to keep the problem clear.
data = {'4': 5, '6': 7}
for j in data:
print repr(j)
test = [{'ad': j['ad'], 'token':j['token']} for j in data]
Running this results in
'4'
'6'
Traceback (most recent call last):
File "x.py", line 6, in <module>
test = [{'ad': j['ad'], 'token':j['token']} for j in data]
TypeError: string indices must be integers, not str
Your print statement shows that iterating through data
produces strings so it makes sense that j['token']
will fail. From the looks of your code, it seems like you want to create a list of dicts from a list of dicts as input. And once you put the input dicts in a list, it ... well crashes because the dicts don't have the keys you claim... but is closer!
Upvotes: 1