2017-07-22 29 views
-2

能否請你讓我知道,如果我有一個像如何讀取數據從靜止URL和加載到一個列表,Python的

http://domain.ca/ArcGIS/rest/services/appData?f=json&pretty=true 

休息服務URL看起來像

{"currentVersion" : 10.05, 
    "folders" : [], 
    "services" : [ 
    {"name" : "appData/Drainage", "type" : "MapServer"}, 
    {"name" : "appData/Parks", "type" : "MapServer"}, 
    {"name" : "appData/Planning", "type" : "MapServer"}, 
    {"name" : "appData/QNet", "type" : "MapServer"}, 
    {"name" : "appData/Sanitary", "type" : "MapServer"}, 
    {"name" : "appData/Street_Lights", "type" : "MapServer"}, 
    {"name" : "appData/Survey", "type" : "MapServer"}, 
    {"name" : "appData/Transportation", "type" : "MapServer"}, 
    {"name" : "appData/Water", "type" : "MapServer"} 
    ] 
} 

如何可以在appData/之後將所有名稱加載到Python中的名爲servicesList的列表中? 我試過類似

myUrl = "http://domain.ca/ArcGIS/rest/services" 
myRequest = myUrl 
response = urllib2.urlopen(myRequest) 
myJSON = response.read() 

但不確定這種正確的方法?!

+0

發生了什麼文件,當你嘗試了,你說你的方法是什麼? – Vib

+0

使用json模塊使用'json.loads(myJSON)'解析這個json。它會將它轉換成一個Python字典,從中你可以得到服務密鑰,它將返回一個字典列表。獲取列表中每個字典的名稱屬性,並將字符串「appData /」替換爲「」,並將結果追加到服務列表中 – technusm1

+0

獲取'urllib2.HTTPError:HTTP錯誤404:未找到類別' –

回答

1
serviceList= [] 
    for x in myJSON["services"]: 
     name = x["name"] 
     serviceList.append(name[name.index("/")+1:]) #Find the index of the/and add everything after it to the list 

這將循環遍歷服務所有的名字和你想要的/後添加部分服務列表。

編輯: 您還必須先將您讀取的字符串轉換爲JSON。要做到這一點:

import json 
newJSON = json.loads(myJSON) 

您可以找到有關JSON here

+0

謝謝anon,但我得到這個錯誤'ValueError:沒有JSON對象可以被解碼'on \t'newJSON = json.loads myJSON)' – Behseini

相關問題