从json.loads

时间:2015-12-18 17:22:18

标签: python json dictionary python-2.x

以下是我要做的事情:提示输入URL,使用urllib从该URL读取JSON数据,然后从JSON数据中解析并提取注释计数并计算其总和。

以下是我目前在Python中的内容:

import json
import urllib

serviceurl = 'http://python-data.dr-chuck.net/comments_42.json'

while True:
    url = serviceurl + urllib.urlencode(('sensor':'false', 'address' : address))
    print "Retrieving", url
    uh = urllib.urlopen(url)
    data = uh.read()
    print "Retrieved", len(data), "characters"

    try:    js = json.loads(str(data))
    except:     js = None

    print js.dumps(js, indent = 4)

    js = ["comment"][0]["count"]
    lst = list()
    lst.append(js)
    print sum(lst)

以下是JSON数据的样子:

{
  comments: [
    {
      name: "Matthias"
      count: 97
    },
    {
      name: "Geomer"
      count: 97
    }
    ...
  ]
}

我正在使用Python 2.这是我第一次这样做,所以你可以给我的任何反馈都会有所帮助,特别是在try / except语句之后。提前谢谢。

8 个答案:

答案 0 :(得分:2)

js是一个如下字典:

{'comments': [{'count': 97, 'name': 'Matthias'}, {'count': 97, 'name': 'Geomer'}]}

您可以获得所有'count'值的总和,如下所示:

sum(nested_dict['count'] for nested_dict in js['comments'])

如果列表中的某个词典可能没有'count'键,请使用默认值为0的dict.get

sum(nested_dict.get('count', 0) for nested_dict in js['comments'])

答案 1 :(得分:1)

我也做了相同的课程并且在同一个任务上。 timgeb的答案将以较小的代码完成工作。或者,您也可以尝试以下方法:

import json
import urllib
counts = list()
inp = raw_input('Enter a URL: ')

url = urllib.urlopen(inp)
data = url.read()
print len(data)

try:
    js = json.loads(data)
except:
js = None

comments = js['comments']
for comment in comments:
    counts.append(comment['count'])

print sum(counts)

#print sum(nested_dict['count'] for nested_dict in js['comments'])

你不需要对url进行任何编码,也不需要while循环。该段代码用于使用Google地图API。

答案 2 :(得分:1)

我的代码版本:

import json
import urllib.request, urllib.parse, urllib.error
total = 0

url = input('Enter URL: ')
data = urllib.request.urlopen(url).read().decode()

info = json.loads(data)
number = info["comments"] #getting list of all the dictinaries
for i in number: #in each dictionary...
    needed = i.get('count') #... we are getting numbers from "count"
    total = total + int(needed) #summ all the numbers
print(total)

答案 3 :(得分:0)

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

# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

url = input('Enter - ')
print('Retrieving', url)
uh = urllib.request.urlopen(url, context=ctx)
data = uh.read()

info = json.loads(data)
#print(info) #to see the info dictionary/object
#print(json.dumps(info, indent=2))  

count = 0
sum = 0

for item in info['comments']:
    num = item['count']
    sum = sum + int(num)
    count = count + 1

print('Count: ', count)
print('Sum: ', sum)

答案 4 :(得分:0)

Dart: Show Main Code Lens

答案 5 :(得分:0)

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

# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

while True:
    count = sum = 0
    url = input('Enter location: ')
    if len(url) < 1: break
    print('Retrieving', url)
    uh = urllib.request.urlopen(url, context=ctx)
    
    data = uh.read()
    print('Retrieved', len(data), 'characters')
    
    info = json.loads(data)

    for item in info['comments']:
        count+=1
        sum+=int(item['count'])
    
    print('count:',count)
    print('sum',sum)

答案 6 :(得分:0)

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

#to ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

url = input('Enter - ')
data = urllib.request.urlopen(url, context=ctx).read()
info = json.loads(data)
sum_count = 0
for a in info["comments"]:
    sum_count += int(a["count"])
print(sum)

答案 7 :(得分:-1)

import json
import urllib

url=raw_input('Enter location:')
print 'Retrieving',url
uh=urllib.urlopen(url)
data=uh.read()


info = json.loads(data)
print 'Retrieved', len(info)
sum=0
counts=0
for item in info['comments']:
    sum=sum+item['count']
    counts=counts+1
print 'Counts:',counts
print 'Sum:',sum