tags:

views:

142

answers:

3

I'm working with dicts in jython which are created from importing/parsing JSON. Working with certain sections I see the following message:

TypeError: str indices must be integers

This occurs when I do something like:

if jsondata['foo']['bar'].lower() == 'baz':
    ...

Where jsondata looks like:

{'foo': {'bar':'baz'} }

What does this mean, and how do I fix it?

+1  A: 

Actually your statement should raise SyntaxError: can't assign to function call due to the fact that you're missing a = and thus making an assignment instead of a check for equality.

Since I don't get the TypeError when running the code you've shown, I suppose that you first fix the missing = and after that check back on what the Stacktrace says.

But it might also be possible that your jsondata hasn't been decoded and therefore is still plain text, which would of course then raise the indexing error.

Ivo Wetzel
Sorry, fixed the typo
digitala
+2  A: 

As Marcelo and Ivo say, it sounds like you're trying to access the raw JSON string, without first parsing it into Python via json.loads(my_json_string).

Daniel Roseman
+1  A: 

You need to check the type for dict and existance of 'z' in the dict before getting data from dict.

>>> jsondata = {'a': '', 'b': {'z': True} }
>>> for key in jsondata:
...     if type(jsondata[key]) is dict and 'z' in jsondata[key].keys() and jsondata[key]['z'] is True:
...         print 'yes'
...
yes
>>>

or shorter one with dict.get

>>> jsondata = {'a': '', 'b': {'z': True}, 'c' :{'zz':True}}
>>> for key in jsondata:
...     if type(jsondata[key]) is dict and jsondata[key].get('z',False):
...         print 'yes'
...
yes
>>>
S.Mark