我正在使用Python解析英國警察API。我想要的是分析我得到的JSON響應,以計算某個進攻發生的次數。這是來自API的響應示例。計算JSON元素中元素的出現次數
{
category: "anti-social-behaviour",
location_type: "Force",
location: {
latitude: "53.349920",
street: {
id: 583315,
name: "On or near Evenwood Close"
},
longitude: "-2.657889"
},
context: "",
outcome_status: null,
persistent_id: "",
id: 22687179,
location_subtype: "",
month: "2013-03"
},
使用此代碼
from json import load
from urllib2 import urlopen
import json
url = "http://data.police.uk/api/crimes-street/all-crime?lat=53.396246&lng=-2.646960&date=2013-03"
json_obj = urlopen(url)
player_json_list = load(json_obj)
for player in player_json_list:
crimeCategories = json.dumps(player['category'], indent = 2, separators=(',', ': '))
print crimeCategories
我得到這樣
"anti-social-behaviour"
"anti-social-behaviour"
"anti-social-behaviour"
"anti-social-behaviour"
"drugs"
"drugs"
"burglary"
的響應。如果我改變了我的for循環
for player in player_json_list:
crimeCategories = json.dumps(player['category'], indent = 2, separators=(',', ': '))
print crimeCategories.count("drugs")
然後我得到這樣的迴應
0
0
0
0
1
1
0
搜索論壇小時沒有幫助我!有任何想法嗎?
@martineau,謝謝,它看起來更好;) – 2015-03-02 21:51:26
我個人認爲,使用'print(dict(c))'看起來會更好。 – martineau 2015-03-02 21:53:58
@martineau,在下面添加了pprint輸出 – 2015-03-02 21:58:48