Home > database >  why am i getting this TypeError: string indices must be integers
why am i getting this TypeError: string indices must be integers

Time:08-24

I have this dictionary

response = {'body': '{"error": "Validation error'}','statusCode': 400}

i want to get the element "error"

print(response["body"]["error"])

but this gives me

TypeError: string indices must be integers

where am i going wrong

CodePudding user response:

You issue is with the superfluous 's:

$ python test.py
  File "C:\Users\pdunn\Downloads\test\test.py", line 1
    response = {'body': '{"error": "Validation error'}','statusCode': 400}
                                                      ^
SyntaxError: invalid syntax

Remove them and it'll work:

response = {"body": {"error": "Validation error"}, "statusCode": 400}
print(response["body"]["error"])
$ python test.py
Validation error

Also, as advice, be consistent with ' and ".

CodePudding user response:

Probably response["body"] is a string (not a dictionary as you are treating it as).

Try printing its type with:

print(type(response["body"]))

If it is str, then you can make it a dict with the json module:

import json
body = json.loads(response["error"])
print(body["error"])
  • Related