Access values from a python json

Asked

Viewed 84 times

2

I have the following python code

import requests
import json

data = requests.get('https://proxycheck.io/v2/42.131.121.100?vpn=1&asn=1')

print(data.text)

That will return:

{
    "status": "ok",
    "42.131.121.100": {
        "continent": "Asia",
        "country": "China",
        "isocode": "CN",
        "latitude": 34.7725,
        "longitude": 113.7266,
        "proxy": "no",
        "type": "Business"
    }
}

How do I display only what is in "country"?

3 answers

3


If you want to work with json instead of using data.text utilize data.json

import requests

data = requests.get('https://proxycheck.io/v2/42.131.121.100?vpn=1&asn=1')
j = data.json()

j['42.131.121.100']['country']

2

You can use the following code to access the obj "42.131.121.100":

print(data.text["42.131.121.100"]["country"])
  • 1

    How are you indexing the keys if data.text is a string?

1

import requests
import json


#Pode-se utilizar dicionario python para acessar conteudo no formato json
#Acessar conteudo por chaves ou valores.
#para acessar só indicar a chave  
# exemplo
#item["country"],item["continent"]

for item in json.loads(requests.get('https://proxycheck.io/v2/42.131.121.100?vpn=1&asn=1').text).values():
  if item  != "ok":
   print(item["country"])

Browser other questions tagged

You are not signed in. Login or sign up in order to post.