Remove Backslash from JSON string?
Asked Answered
S

2

9

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
Seabolt answered 19/7, 2017 at 14:18 Comment(0)
S
4

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.

Sevenup answered 19/7, 2017 at 15:19 Comment(1)
Thanks for the answer. Actually i am doing mistake using replace function format. Thanks once again for the answer.Seabolt
J
9

you need to first use dumps then loads

json_data = json.dumps(response_read)
json_without_slash = json.loads(json_data)
Jelks answered 7/6, 2021 at 8:46 Comment(0)
S
4

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.

Sevenup answered 19/7, 2017 at 15:19 Comment(1)
Thanks for the answer. Actually i am doing mistake using replace function format. Thanks once again for the answer.Seabolt

© 2022 - 2024 — McMap. All rights reserved.