Home > OS >  Parsing JSON response for individual value
Parsing JSON response for individual value

Time:11-23

I'm having trouble parsing the below JSON Response Dict object to just return/print the 'data' value (testing.test.com). See the dict below:

[{'_id': '~1742209152', 'id': '~1742209152', 'createdBy': '[email protected]', 
'createdAt': 1666089754558, '_type': 'case_artifact', 'dataType': 'domain', 'data': 
'testing.test.com', 'startDate': 1666089754558, 'tlp': 2, 'pap': 2, 'tags': 
['Domain'], 'ioc': True, 'sighted': True, 'message': '', 'reports': {}, 'stats': {}, 
'ignoreSimilarity': False}]

Whenever I go to run the following code to attempt to parse the data, I'm shown an error 'print(observables['data'])TypeError: list indices must be integers or slices, not str':

    observables = json.dumps(response) #getting JSON response dict which works fine
    print(observables) #printing is successful

    print(observables['data']) #issue is here

I realise the error is suggesting I use int rather than string, but when I try to reverse this, it doesn't work and sends me on an endless number of errors. Is there a specific way to do this? I'm not overly confident in my scripting abilities so appreciate any pointers!

Ps - as a side note, this interaction is occurring been an API and my python file, but since I'm only having issues with the JSON response return parsing, I doubt that has any impact.

CodePudding user response:

your response is a list of dict objects. note that the first opening brackets are [ and not {.

you need to address the first (and only) object in your example and then access it as a dict using the 'data' key.

try print(observables[0]['data'])

EDIT: after seeing more of the code in chat room, and figuring out you used dumps() on the response object. I figured out that you're handling a string, and not a list/dict.

you should remove the call to dumps() since you're getting a requests.Response object as a response, you can just do: observables = response.json() and then continue with the original answer.

  • Related