Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: string indices must be integers while parsing JSON using Python?

I am confuse now why I am not able to parse this JSON string. Similar code works fine on other JSON string but not on this one - I am trying to parse JSON String and extract script from the JSON.

Below is my code.

for step in steps:     step_path = '/example/v1' +'/'+step      data, stat = zk.get(step_path)     jsonStr = data.decode("utf-8")     print(jsonStr)     j = json.loads(json.dumps(jsonStr))     print(j)     shell_script = j['script']     print(shell_script) 

So the first print(jsonStr) will print out something like this -

{"script":"#!/bin/bash\necho Hello world1\n"} 

And the second print(j) will print out something like this -

{"script":"#!/bin/bash\necho Hello world1\n"} 

And then the third print doesn't gets printed out and it gives this error -

Traceback (most recent call last):   File "test5.py", line 33, in <module>     shell_script = j['script'] TypeError: string indices must be integers 

So I am wondering what wrong I am doing here?

I have used same above code to parse the JSON and it works fine..

like image 549
AKIWEB Avatar asked Nov 19 '13 23:11

AKIWEB


People also ask

How do I fix error string indices must be integers in Python?

The Python "TypeError: string indices must be integers" occurs when we use a non-integer value to access a string at an index. To solve the error, make sure to use an integer, e.g. my_str[2] or a slice, e.g. my_str[0:3] when accessing a string at a specific index.

How do you parse a json string in Python?

If you have a JSON string, you can parse it by using the json.loads() method. The result will be a Python dictionary.

Why am I seeing TypeError string indices must be integers?

The typeerror: string indices must be integers indicates that we are attempting to access a value from an iterable using a string index rather than an integer index. The iterable objects are indexed using numbers. Therefore, an error will be returned when you try to obtain an iterable object using a string value.

How do you resolve string indices must be integers?

1 comment. String indices must be integers. This means that when you're accessing an iterable object like a string, you must do it using a numerical value. If you are accessing items from a dictionary, make sure that you are accessing the dictionary itself and not a key in the dictionary.


2 Answers

The problem is that jsonStr is a string that encodes some object in JSON, not the actual object.

You obviously knew it was a string, because you called it jsonStr. And it's proven by the fact that this line works:

jsonStr = data.decode("utf-8") 

So, jsonStr is a string. Calling json.dumps on a string is perfectly legal. It doesn't matter whether that string was the JSON encoding of some object, or your last name; you can encode that string in JSON. And then you can decode that string, getting back the original string.

So, this:

j = json.loads(json.dumps(jsonStr)) 

… is going to give you back the exact same string as jsonStr in j. Which you still haven't decoded to the original object.

To do that, just don't do the extra encode:

j = json.loads(jsonStr) 

If that isn't clear, try playing with it an interactive terminal:

>>> obj = ['abc', {'a': 1, 'b': 2}] >>> type(obj) list >>> obj[1]['b'] 2 >>> j = json.dumps(obj) >>> type(j) str >>> j[1]['b'] TypeError: string indices must be integers >>> jj = json.dumps(j) >>> type(jj) str >>> j '["abc", {"a": 1, "b": 2}]' >>> jj '"[\\"abc\\", {\\"a\\": 1, \\"b\\": 2}]"' >>> json.loads(j) ['abc', {'a': 1, 'b': 2}] >>> json.loads(j) == obj True >>> json.loads(jj) '["abc", {"a": 1, "b": 2}]' >>> json.loads(jj) == j True >>> json.loads(jj) == obj False 
like image 60
abarnert Avatar answered Sep 25 '22 08:09

abarnert


Try replacing j = json.loads(json.dumps(jsonStr)) with j = json.loads(jsonStr).

like image 27
1st1 Avatar answered Sep 23 '22 08:09

1st1