I am trying to convert this string into a json object : -
coordinates = "{ lat: '55,7303650017903', lng: '12,3446636123658' }"
I tried using json.loads(), it didn't work for me. Is there a way I can achieve this?
-
string looks like javascript objectTibin– Tibin2020年03月09日 11:05:04 +00:00Commented Mar 9, 2020 at 11:05
-
I was just about to comment as per @Chris Doyles comment -- this is not a python dictionary as your keys do not have quotes around themAlan Kavanagh– Alan Kavanagh2020年03月09日 11:05:04 +00:00Commented Mar 9, 2020 at 11:05
-
1The problem you have is that this string is neither a valid python dict nor valid json object.Chris Doyle– Chris Doyle2020年03月09日 11:06:32 +00:00Commented Mar 9, 2020 at 11:06
-
Okay. Thanks for the correction. But is there a way I can retrieve the value of a key? For example , the value of 'lat'Derrick Omanwa– Derrick Omanwa2020年03月09日 11:09:53 +00:00Commented Mar 9, 2020 at 11:09
4 Answers 4
I recommend using demjson python parser for achieving this , since the string is js object
import demjson
print(demjson.decode("{ lat: '55,7303650017903', lng: '12,3446636123658' }"))
2 Comments
Using regex to add quotes around the key and then use the ast module
Ex:
import re
import ast
coordinates = "{ lat: '55,7303650017903', lng: '12,3446636123658' }"
coordinates = re.sub(r"(\w+)(?=:)", r'"1円"', coordinates)
print(ast.literal_eval(coordinates))
Output:
{'lat': '55,7303650017903', 'lng': '12,3446636123658'}
Comments
A possible solution would be to use a regular expression:
import re
coordinates = "{ lat: '55,7303650017903', lng: '12,3446636123658' }"
pattern = r"{ lat: '(.*)', lng: '(.*)' }"
lat, lng = re.findall(pattern, coordinates)[0]
This solution does not require importing any additional packages beyond re. If you want then want a dictionary with those values:
cords = { "lat": lat, "lng": lng }
Comments
You need to use json.loads:
import json
coordinates = '{ "lat": "55,7303650017903", "lng": "12,3446636123658" }'
datastore = json.loads(coordinates)
print(json.dumps(datastore))
You can try in an online repl: https://repl.it/languages/python3