0

I have a json output from http request like this:

print(resp)
{'totalCount': 1, 'pageSize': 50, 'entities': [{'entityId': 'HOST-12345', 'displayName': 'beff'}]}
{'totalCount': 1, 'pageSize': 50, 'entities': [{'entityId': 'HOST-7898', 'displayName': 'dude101'}]}
{'totalCount': 1, 'pageSize': 50, 'entities': [{'entityId': 'HOST-56890', 'displayName': 'prop'}]}

I need to grab the entityId from this list:

HOST-12345
HOST-7898
HOST-56890

I have this:

print(resp['entities']['entityId'])

I get this error:

TypeError: list indices must be integers or slices, not str
2
  • 1
    use resp['entities'][0]['entityId'] Commented Jan 12, 2022 at 17:19
  • resp['entities'] is a list with a single element... You need to first take that single element by indexing the list with [0] and then you get the dict to access with ['entityId'] Commented Jan 12, 2022 at 17:27

2 Answers 2

1

Your current response is not in JSON format, in fact it is a string ! if this is what it is, you need to first split it with "\n" to get every line as a list item. Then you need to convert ' to " (JSON doesn't support single quotation).

Now it is in JSON format and you can decode it with json.loads() to get the dictionary object and get information from it:

import json

txt = """{'totalCount': 1, 'pageSize': 50, 'entities': [{'entityId': 'HOST-12345', 'displayName': 'beff'}]}
{'totalCount': 1, 'pageSize': 50, 'entities': [{'entityId': 'HOST-7898', 'displayName': 'dude101'}]}
{'totalCount': 1, 'pageSize': 50, 'entities': [{'entityId': 'HOST-56890', 'displayName': 'prop'}]}"""

for line in txt.split('\n'):
    correct_json_format = line.replace("'", '"')
    d = json.loads(correct_json_format)
    print(d['entities'][0]['entityId'])

output:

HOST-12345
HOST-7898
HOST-56890
Sign up to request clarification or add additional context in comments.

Comments

0

indices are always number, so to access line number 1 you have to write resp[0], now using dots (.) you can access the inside fields.

print(resp[0]['entities'][0]['entityId'])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.