user1471980
user1471980

Reputation: 10626

how do you extract from the json output using python

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

Upvotes: 0

Views: 51

Answers (2)

p kushwaha
p kushwaha

Reputation: 407

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'])

Upvotes: 0

S.B
S.B

Reputation: 16476

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

Upvotes: 1

Related Questions