Search code examples
jsonpython-2.7urllib2geospatialurllib

Remove Backslash from JSON string?


I am using python url library to get json response from spatial reference website.This is my code. I get response_read="u'{\'type\': \'EPSG\', \'properties\': {\'code\': 102646}}'" but i need this response in this form:"{'type': 'EPSG', 'properties': {'code': 102646}}". How i achieve output in this form?

headers = {'User-Agent': 'Mozilla/5.0'}
 req = urllib2.Request("http://spatialreference.org/ref/esri/"nad-1983-stateplane-california-vi-fips-0406-feet"/json/", None, headers)
        response = urllib2.urlopen(req)
        response_read = response.read().decode('utf-8')
        result = json.dumps(response_read)  
        epsg_json = json.loads(result)
        epsg_code = epsg_json['properties']['code']
        return epsg_code

Solution

  • I am not very sure your is a function or not. Anyways, the response you receive is having the literal character ' and you need to replace it with ".

    Here is the working code:

    import urllib2,json
    headers = {'User-Agent': 'Mozilla/5.0'}
    req = urllib2.Request("http://spatialreference.org/ref/esri/nad-1983-stateplane-california-vi-fips-0406-feet/json/", None, headers)
    response = urllib2.urlopen(req)
    response_read = response.read()
    epsg_json = json.loads(response_read.replace("\'", '"'))
    epsg_code = epsg_json['properties']['code']
    print(epsg_code)
    

    Hope this helps.