How to read data from a REST URL and load to a list in Python
Question:
I have a rest service URL like:
http://domain.ca/ArcGIS/rest/services/appData?f=json&pretty=true
which looks like:
{"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"}
]
}
How can load all names after appData/
to a list called servicesList
in Python? I tried something like
myUrl = "http://domain.ca/ArcGIS/rest/services"
myRequest = myUrl
response = urllib2.urlopen(myRequest)
myJSON = response.read()
Is the the correct way?
Answers:
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
This would loop over all the names in the services and add the part after the /
to the service list as you want.
EDIT:
You will also have to convert the string you read to JSON first. To do that:
import json
newJSON = json.loads(myJSON)
You can find documentation about json here
I have a rest service URL like:
http://domain.ca/ArcGIS/rest/services/appData?f=json&pretty=true
which looks like:
{"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"}
]
}
How can load all names after appData/
to a list called servicesList
in Python? I tried something like
myUrl = "http://domain.ca/ArcGIS/rest/services"
myRequest = myUrl
response = urllib2.urlopen(myRequest)
myJSON = response.read()
Is the the correct way?
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
This would loop over all the names in the services and add the part after the /
to the service list as you want.
EDIT:
You will also have to convert the string you read to JSON first. To do that:
import json
newJSON = json.loads(myJSON)
You can find documentation about json here