'Fetch a single word from an output in python?
I need to fetch a single character from an output and put it in if statement.
I enter this
cloud_name = os.system(" curl ipinfo.io ")
print(cloud_name)
curl ipinfo.io 127 ⨯
{
"ip": "",
"hostname": "broadband.actcorp.in",
"city": "Bengaluru",
"region": "Karnataka",
"country": "IN",
"loc": "",
"org": "AS24309 Atria Convergence Technologies Pvt. Ltd. Broadband Internet Service Provider INDIA",
"postal": "",
"timezone": "Asia/Kolkata",
"readme": "https://ipinfo.io/missingauth"
}
in this output i have to just check if Convergence is present in the org line.
How do i do that in python?
Solution 1:[1]
You can do so with the requests library:
import requests
resp = requests.get("https://ipinfo.io")
if "Convergence" in resp.json().get("org", ""):
print("yay")
note: This requires the installation of requests which is not in python standard library. It can be installed a few ways. One example is pip install requests, but here is the official installation guide
Solution 2:[2]
Using the requests module to GET the JSON response from that URL would be a better approach.
If however you insist on running curl you could do this:
import subprocess
import json
data = json.loads(subprocess.Popen('curl ipinfo.io', stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, shell=True).stdout.read())
if 'Convergence' in data['org']:
print('Convergence found')
else:
print('Not found')
This is how you could do it using requests:
import requests
(r := requests.get('https://ipinfo.io')).raise_for_status()
if 'Convergence' in r.json()['org']:
print('Convergence found')
else:
print('Not found')
Solution 3:[3]
if 'Convergence' in variable_name['org']:
print('Do Something')
Note that JSON is not inside any varible. So do this:
x = {Your JSON file HERE}
so check it like this:
if 'Convergence' in x['org']:
print('Do Something')
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Albert Winestein |
| Solution 3 |
