0

I'm making a request to a REST API endpoint:

import requests
import json
response = requests.get(<URL>, headers=headers)

I get the following when doing a print json.loads(response.content):

{'data': [{'reference': '123', 'name': 'example', 'risk': 'LOW', 'status': 'tbd', 'Description': None, 'found': '2021-04-21', 'last_tested': None, 'resolved': '2021-04-29', 'notes': 'legacy', 'clientid': {'clientname': 'xyz'}, 'categoryid': {'category': 'test1'}, 'subcategoryid': {'SubCategory': 'test2'}}]}

Is this valid JSON? I am getting errors and it seems to stem from the "[" to the right of "data". For example, how would I access the 'reference' value, and even the 'category' (nested) value?

Example, doing this:

print (json_response["data"]["reference"])

Results in:

list indices must be integers or slices, not str
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
mbr_uk
  • 33
  • 7
  • Yes, it's valid. It wouldn't parse otherwise. But you need to access it based on the actual structure it has. – jonrsharpe Jul 08 '22 at 17:39
  • `json_response["data"]` is a list containing one dictionary. You're looking for `json_response["data"][0]["reference"]` – Paul M. Jul 08 '22 at 17:41
  • should be data[0]['reference']. since the value of 'data' in that response is a list – smcrowley Jul 08 '22 at 17:41
  • You can use `response.json`, it will parse it automatically for you. – Barmar Jul 08 '22 at 17:43
  • BTW, it looks like you're using Python 2.x. That version has passed end-of-life, you should upgrade to Python 3.x. – Barmar Jul 08 '22 at 17:43

1 Answers1

0

try it !

print(json_response["data"][0]["reference"])
Willian Vieira
  • 646
  • 3
  • 9
  • Thanks all. Just tried in @WillianVieira and worked like a charm. Can't believe I didn't see that one, so simple. – mbr_uk Jul 09 '22 at 16:13