Theron Moustakes
Theron Moustakes

Reputation: 21

Print Multiple JSON Data Fields for Same Category in Python (Only Printing First Value)

I would like to be able to parse out a certain variable in a JSON array. My script allows the user to enter lat/lon/SKU as the URL is built around these parameters. Then, I want to print the JSON data, but I only care able one variable: "AddressCityStateZip". The code works perfectly... when there is only one "set of variables" (I apologize for the lack of terminology) but yet, when more than one store is returned in the result, I only get the FIRST value returned. Example being, if this JSON is returned:

[{"DisplayName":"Bridgewater Plaza","AddressStreet":"233 Broad ST","AddressCityStateZip":"Bridgewater, MA 02324","Phone":"5086970422","Latitude":41.996038893609,"Longitude":-70.9730786855837,"DistanceNumber":1.4091862149476761089787,"Distance":"1.4 Mi","StoreNumber":3776,"IsNewAvailable":false,"IsPreOwnedAvailable":true,"IsDigitalAvailable":true,"IsHopsEnabled":true},{"DisplayName":"Crescent Plaza","AddressStreet":"715 Crescent St","AddressCityStateZip":"Brockton, MA 02302","Phone":"5084275334","Latitude":42.0811691880226,"Longitude":-70.9903740137815,"DistanceNumber":5.62995717249044434817,"Distance":"5.6 Mi","StoreNumber":2225,"IsNewAvailable":false,"IsPreOwnedAvailable":true,"IsDigitalAvailable":true,"IsHopsEnabled":true},

I would ONLY get "Bridgewater, MA 02324" printed, instead of BOTH "Bridgewater, MA 02324" AND "Brockton, MA 02302".

Here's a portion of my code to compute this, what am I doing wrong?

lat = raw_input("Enter the lat: ")  #THIS IS WHERE WE NEED TO STORE VALUES OPENED FROM FILE: LATS.CSV (OR LATS.TXT ?)
lon = raw_input("Enter the lon: ")  #THIS IS WHERE WE NEED TO STORE VALUES OPENED FROM FILE: LONS.CSV (OR LONS.TXT ?)
sku = raw_input("Enter the SKU: ")  #THIS IS WHERE WE STORE USER INPUT FOR GAME SKU. ITS /NOT/ DERIVED FROM A FILE...YET.


url = "http://www.gamestop.com/PickUpAtStore/Stores/GetStoresByLocation?latitude=%s&longitude=-%s&newSku=&usedSku=%s&digitalSku=%s&displayMode=HOPS&displaySku=%s" % (lat, lon, sku, sku, sku)

print
print url
print

r = requests.get(url,)

mm = r.json()[0]["AddressCityStateZip"]
print mm

Upvotes: 2

Views: 1375

Answers (1)

Mureinik
Mureinik

Reputation: 311723

You are just printing the first element in the json array by accessing it with [0]. Instead, you could loop over it:

for j in r.json():
    print j["AddressCityStateZip"]

Upvotes: 1

Related Questions