-1

I have a database full of those strings:

'"type":"Feature","geometry":{"type":"Polygon","coordinates":[[[4.916520921976682,43.58795128864228],[4.916519615794914,43.58792348750154],[4.916427403085649,43.58792577651196],[4.916428709224705,43.58795357765377],[4.916520921976682,43.58795128864228]]]},"properties":{"color":"blue","shapeRepresents":"string","name":"G11.01/2"},"id":"1823481"'

and I need to read them as a python dictionary. I tried eval() but it says invalid syntax. Any idea or suggestion?

buran
  • 13,682
  • 10
  • 36
  • 61
  • Does this answer your question? [Convert a String representation of a Dictionary to a dictionary?](https://stackoverflow.com/questions/988228/convert-a-string-representation-of-a-dictionary-to-a-dictionary) – Tomerikoo Oct 29 '20 at 15:02

1 Answers1

3

this is malformed JSON. Enclose in curly brackets and use json module to parse it.

spam = '"type":"Feature","geometry":{"type":"Polygon","coordinates":[[[4.916520921976682,43.58795128864228],[4.916519615794914,43.58792348750154],[4.916427403085649,43.58792577651196],[4.916428709224705,43.58795357765377],[4.916520921976682,43.58795128864228]]]},"properties":{"color":"blue","shapeRepresents":"string","name":"G11.01/2"},"id":"1823481"'
import json
from pprint import pprint
eggs = json.loads(f'{{{spam}}}')
pprint(eggs)

output

{'geometry': {'coordinates': [[[4.916520921976682, 43.58795128864228],
                               [4.916519615794914, 43.58792348750154],
                               [4.916427403085649, 43.58792577651196],
                               [4.916428709224705, 43.58795357765377],
                               [4.916520921976682, 43.58795128864228]]],
              'type': 'Polygon'},
 'id': '1823481',
 'properties': {'color': 'blue',
                'name': 'G11.01/2',
                'shapeRepresents': 'string'},
 'type': 'Feature'}

Note, after adding curly brackets you can use ast.literal_eval() instead of json.loads(). Your eval() will also work, but it is discouraged.

buran
  • 13,682
  • 10
  • 36
  • 61