-3

I have to parse and get the 'id' field value alone (i.e 13 in this case) from the below JSON response. My JSON response will be in the below format. This is get policies nessus call

{'policies': [{'creation_date': 1546583582,
               'description': 'New Scan',
               'has_credentials': 0,
               'id': 13}]}

My code:

import requests
from first import *
url = 'https://localhost:8834/policies'
headers = {'X-Cookie':mys()}
response = requests.get(url, headers=headers, verify=False)
resp = response.json()
for k,v in resp.items():
    print (v)

Code response:

[{'creation_date': 1546583582,'description': 'New Scan','has_credentials': 0,'id': 13}]

I'm unsure how to write a code to get the result as expected response - 'id' : 13 or just 13.

martineau
  • 119,623
  • 25
  • 170
  • 301
  • 3
    Say you call the list at the end `a`. Then it would be `a[0][‘id’]`. – Jack Moody Jan 08 '19 at 08:18
  • @JackMoody : bro! I get the entire file([{'creation_date': 1546583582,'description': 'New Scan','has_credentials': 0,'id': 13}]) as part of response = requests.get(url, headers=headers, verify=False) but I need to know how to print 'id'=13 value alone? – Madhan baskar Jan 08 '19 at 08:26
  • 1
    I think @JackMoody meant, put in terms of your code, to use `print(v[0]['id'])`. – martineau Jan 08 '19 at 08:40

2 Answers2

0

You could do it either of these ways:

resp = {'policies': [{'creation_date': 1546583582,
                      'description': 'New Scan',
                      'has_credentials': 0,
                      'id': 13}]}

for k,v in resp.items():
    print(v[0]['id'])  # -> 13

# or

print(resp.popitem()[1][0]['id'])  # -> 13
martineau
  • 119,623
  • 25
  • 170
  • 301
0

In case when you have several policies and want to extract ids to list you can use a list comprehension like [policy.get('id') for policies in resp.values() for policy in policies] thus you'll get a list of ids

the alternative is loop:

for policies in resp.values(): for policy in policies: print(policy.get('id'))

Bohdana
  • 11
  • 1