简体   繁体   中英

Appending json response to a list

I'm having trouble appending a json response into a list. I'm sure it's a simple error but have spent hours trying to figure this out . . . any suggestion(s) would be greatly appreciated.

edd_areas = ["San Francisco-Redwood City-South San Francisco MD", 
             "Los Angeles-Long Beach-Glendale MD", 
             "Oakland-Hayward-Berkeley MD",
             "California"]

edd_year = []

edd_url = "https://data.edd.ca.gov/resource/4ezp-3bs3.json?"

for area in edd_areas:
    edd_query_url = edd_url + "area_name=" + area + "&seasonally_adjusted_y_n=N"
    edd_qresponse = requests.get(edd_query_url).json

    edd_year.append(edd_qresponse["year"])

Error: 
TypeError                                 Traceback (most recent call last)
<ipython-input-10-f3a906010984> in <module>()
     17 
     18 
---> 19     edd_year.append(edd_qresponse["year"])

TypeError: 'method' object is not subscriptable

Two things:

The first issue is in requests.get(edd_query_url).json . .json is a method and doesn't return json data, you were probably trying to do .json() instead and actually get the data.

The second issue is that the actual json data is a list so you can't index it by strings like "year".

Putting everything together:

edd_areas = ["San Francisco-Redwood City-South San Francisco MD", 
         "Los Angeles-Long Beach-Glendale MD", 
         "Oakland-Hayward-Berkeley MD",
         "California"]

edd_year = []

edd_url = "https://data.edd.ca.gov/resource/4ezp-3bs3.json?"

for area in edd_areas:
    edd_query_url = edd_url + "area_name=" + area + "&seasonally_adjusted_y_n=N"
    edd_qresponse = requests.get(edd_query_url).json() # call the function!

    edd_year.append(edd_qresponse) # just append the list since you can't index by "year"

And you get something that looks like this:

[[{'area_name': 'San Francisco-Redwood City-South San Francisco MD', 'area_type': 'Metropolitan Area', 'date': '1990-01-01T00:00:00.000' ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM