import urllib.request
import json
# Open the URL and read the content as bytes
info = urllib.request.urlopen('http://py4e-data.dr-chuck.net/comments_2066892.json ')
content = info.read()
# Decode the bytes to a string
content_str = content.decode('utf-8')
# Parse the JSON string into a Python dictionary
data = json.loads(content_str)
# Initialize the counter
total_count = 0
# Iterate through the comments and sum up the counts
for comment in data.get('comments', []):
total_count += comment.get('count', 0)
# Print the total count of comments
print(f"Total count of comments: {total_count}")
//////////////////////
>>> info=json.loads(urllib.request.urlopen('https://ipinfo.io/json').read().decode('utf-8'))
1) urllib.request.urlopen('https://ipinfo.io/json').read().decode()
a) Open the url
a) Open the url
b) read the data as byte class
c) decode by data to utf as string object
d) json.loads(str object) // create dict from the string object
print(info) // dict
{'ip': '148.0.197.54', 'hostname': '54.197.0.148.d.dyn.claro.net.do', 'city': 'Santo Domingo', 'region': 'Nacional', 'country': 'DO', 'loc': '18.4719,-69.8923', 'org': 'AS6400 Compañía Dominicana de Teléfonos S. A.', 'postal': '10201', 'timezone': 'America/Santo_Domingo', 'readme': 'https://ipinfo.io/missingauth'}
// get dict value
>> ip=json.loads(urllib.request.urlopen('https://ipinfo.io/json').read().decode('utf-8')).get('ip')
ip_r=requests.get('https://ipinfo.io/json').json().get('ip')
>>> print(ip)
'148.0.197.54'
No hay comentarios:
Publicar un comentario