简体   繁体   English

在Python中提取JSON响应的一部分

[英]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. 我是编程的初学者,我正在尝试使用API​​使我的工作自动化。

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 提前谢谢

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
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 如果您有疑问,请告诉我

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM