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?

Asked By: Behseini

||

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

Answered By: anon
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.