Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

I get this error:

TypeError: list indices must be integers or slices, not str

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading