2017-02-25 72 views
2

我想能夠解析出JSON數組中的某個變量。我的腳本允許用戶輸入緯度/經度/ SKU,因爲URL是圍繞這些參數構建的。然後,我想打印JSON數據,但我只關心一個變量:"AddressCityStateZip"。代碼完美地工作......當只有一組「變量」時(我對缺乏術語表示歉意),但是當結果中返回多個商店時,我只返回FIRST值。例子是,如果返回該JSON:在Python中打印同一類別的多個JSON數據字段(僅打印第一個值)

[{"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}, 

我只會得到 「布里奇沃特,MA 02324」 字樣,而不是BOTH 「布里奇沃特,MA 02324」 和 「布羅克,MA 02302」。

這是我的一部分代碼來計算這個,我做錯了什麼?

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 
+2

你聽說過循環? –

回答

1

你只是通過用[0]訪問它打印JSON陣列中的第一個元素。相反,你可以循環它:

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

謝謝!我是一個非常新的使用python和JSON :)我知道一個循環在那裏,只是沒有意識到它是那麼容易 –