Skip to content

Instantly share code, notes, and snippets.

@manichabba
Created August 20, 2016 01:17
Show Gist options
  • Save manichabba/dad7426adcdce2efc652b15940304cb2 to your computer and use it in GitHub Desktop.
Save manichabba/dad7426adcdce2efc652b15940304cb2 to your computer and use it in GitHub Desktop.
====Extracting Data from JSON: ==== The program will prompt for a URL, read the JSON data from that URL using urllib and then parse and extract the comment counts from the JSON data, compute the sum of the numbers in the file and provide the sum.
import urllib #importing urllib
import json #importing json
#requesting a json file url
url = raw_input("Enter the URL:")
#load json file as list -info
info = json.loads(urllib.urlopen(url).read())
x = 0
#loop through each item in list comments
for items in info['comments']:
#loop through the value of the key count in the list and add
x = x + int(items['count'])
print 'count: ',(x)
@fermartz10
Copy link

import urllib.request
import json

url = input("Enter the URL:")

info = json.loads(urllib.request.urlopen(url).read())

x = 0
counts=0
for items in info['comments']:

x = x + int(items['count'])
counts = counts + 1

print ('Counts ',(counts))
print ('Sum : ',(x))

#xd, late

@AidaKok
Copy link

AidaKok commented Jan 7, 2022

Here is a simplified code:

import urllib.request, urllib.parse, urllib.error
import json

url = "The URL"
info = json.loads(urllib.request.urlopen(url).read())

comm=info['comments']
counts_list = [int(items['count']) for items in comm]
print(sum(counts_list))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment