试图在JSON中迭代数据

时间:2018-03-02 05:31:20

标签: json python-3.x for-loop

我为所有警察报告提供了一个REST API,我试图迭代GET请求的结果。

import requests
import json
import time

query = "http://gismaps.wichita.gov/agsweb/rest/services/COWGIS/WPD_Public/MapServer/0/query?where=1%3D1&outFields=CATEGORY,ADDRESS,PBADDRESS,CASEADDRESS,CITY,STARTDATE,DOW,INCMONTH,MONTHHS,OFFENSE_CO,OFFENSE_DE,PLACE_DESC,CLASS_TYPE,Shape,INCREPORT,STARTDATET,STARTTIME&outSR=4326&f=json"
query_value = requests.get(query)
crime = query_value.json()

def search(num):
    for i in range(1, num):
        print(crime["features"][i]["attributes"]["CATEGORY"])


search(10)

此代码返回此数据:

AGG_ASSAULT DISORDERLY VANDALISM DISORDERLY DRUGS DRUGS OTHERTRAF_VIO OTHERTRAF_VIO LARCENY

但是当我运行这段代码时:

import requests
import json
import time

query = "http://gismaps.wichita.gov/agsweb/rest/services/COWGIS/WPD_Public/MapServer/0/query?where=1%3D1&outFields=CATEGORY,ADDRESS,PBADDRESS,CASEADDRESS,CITY,STARTDATE,DOW,INCMONTH,MONTHHS,OFFENSE_CO,OFFENSE_DE,PLACE_DESC,CLASS_TYPE,Shape,INCREPORT,STARTDATET,STARTTIME&outSR=4326&f=json"
query_value = requests.get(query)
crime = query_value.json()

def search(num):
    amt = 0
    for i in range(1, num):
        #print(crime["features"][i]["attributes"]["CATEGORY"])
        value = crime["features"][i]["attributes"]["CATEGORY"]
        print(str(value))
        if str(value) == "DRUGS":
            amt + 1
    print(amt, "matches")


search(10)

它返回" 0匹配",即使它清楚地输出有2个报告的值为" DRUGS",并且它返回我0.帮助将不胜感激

1 个答案:

答案 0 :(得分:0)

amt + 1并没有做太多。要递增计数器,请使用amt += 1