Vanity
Vanity

Reputation: 33

Extract part of JSON response in Python

I'm a beginner in programming, and I'm trying to deal with an API to automate my work.

I'm getting the response just fine, but I'm only interested by 2 values, being host and port.

Here is a part of my code

import requests

url = "https://proxy6.net/api/xxx"

def descr():
    return 88


querystring = {"descr":descr()}

headers = {
    'Cache-Control': "no-cache",
    'Postman-Token': "xxx"
    }

response = requests.request("GET", url, headers=headers, params=querystring)

print(response.text)

How can I print only the host and port value?

Thanks a lot in advance

Upvotes: 0

Views: 4840

Answers (2)

iamabhaykmr
iamabhaykmr

Reputation: 2021

import requests
import json

url = "https://proxy6.net/api/xxx"

def descr():
    return 88


querystring = {"descr":descr()}

headers = {
    'Cache-Control': "no-cache",
    'Postman-Token': "xxx"
    }

response = requests.request("GET", url, headers=headers, params=querystring)
response = response.json()
print(response['list']['xx']['host'])
print(response['list']['xx']['port'])

Explanations:

{"status":"yes","user_id":"xx","balance":"xx","currency":"xx","list_count":1,"list":{"xx":{"id":"xx","version":"x,"ip":"xx","host":"xx","port":xx","user":"xx","pass":"xx","type":"socks","country":"us","date":"2018-09-05 22:00:22","date_end":"2018-10-05 22:00:22","unixtime":1536174022,"unixtime_end":1538766022,"descr":"88","active":"1"}}}


response['list'] gives `{"xx":{"id":"xx","version":"x,"ip":"xx","host":"xx","port":xx","user":"xx","pass":"xx","type":"socks","country":"us","date":"2018-09-05 22:00:22","date_end":"2018-10-05 22:00:22","unixtime":1536174022,"unixtime_end":1538766022,"descr":"88","active":"1"}}`


response['list']['xx']  gives  `{"id":"xx","version":"x,"ip":"xx","host":"xx","port":xx","user":"xx","pass":"xx","type":"socks","country":"us","date":"2018-09-05 22:00:22","date_end":"2018-10-05 22:00:22","unixtime":1536174022,"unixtime_end":1538766022,"descr":"88","active":"1"}`

response['list']['xx']['host'] gives host key value
response['list']['xx']['port'] gives port key value

Do let me know if you have doubts

Upvotes: 2

Mikhail Burshteyn
Mikhail Burshteyn

Reputation: 5012

response = requests.request(...)
data = response.json()
for value in data['list'].values():
    host = value['host']
    port = value['port']

    print host, port  # OP uses Python 2

    break
else:  # we didn't break, which means data['list'] was empty
    raise RuntimeError('Empty list')

response2 = requests.request('POST', ...)  # you can use host and port here

Upvotes: 1

Related Questions