I have text file coordinates.txt, which has data in the below format. I want to read coordinates in each line into python object list of list of float. Each of the bounds will have only 5 lat,long pairs.
{"id": "1b2e1366-9ac7-4220-8dc2-c333d3da6e42", "bounds": "[[-121.02662668533802, 38.39556098724271], [-121.01552400710878, 38.39556098724271], [-121.01552400710878, 38.38638931377034], [-121.02662668533802, 38.38638931377034], [-121.02662668533802, 38.39556098724271]]"}
{"id": "e2c02621-6685-435c-b1f0-07e0bca49870", "bounds": "[[-121.71606277115228, 38.424526411333495], [-121.70496009292305, 38.424526411333495], [-121.70496009292305, 38.41535473786112], [-121.71606277115228, 38.41535473786112], [-121.71606277115228, 38.424526411333495]]"}
{"id": "14d29a1f-e014-43fc-bfcf-b380126e8270", "bounds": "[[-120.64683157721372, 38.77860318996463], [-120.63572889898448, 38.77860318996463], [-120.63572889898448, 38.769431516492254], [-120.64683157721372, 38.769431516492254], [-120.64683157721372, 38.77860318996463]]"}
I’m using the below code to read the value for the key "bounds":
with open(file = coordinates_file_path) as f:
for line in f:
coordinates = json.loads(line)['bounds']
print(coordinates[0]) # this prints only the char `[`
coordinates_data.append(coordinates)
What I want:
coordinates to be a list of size 5, with each element being a list of size 2 of float.
So that I can instantiate a Polygon() object as below:
>>> from geojson import Polygon
>>> Polygon([[(2.38, 57.322), (23.194, -20.28), (-120.43, 19.15), (2.38, 57.322), (2.39, 56.45)]])
{"coordinates": [[[2.3..., 57.32...], [23.19..., -20.2...], [-120.4..., 19.1...], [2.3..., 57.3..]]], "type": "Polygon"}
But with the code I used above, coordinates is just a string of [[-121.02662668533802, 38.39556098724271], [-121.01552400710878, 38.39556098724271], [-121.01552400710878, 38.38638931377034], [-121.02662668533802, 38.38638931377034], [-121.02662668533802, 38.39556098724271]].
2
Answers
Using python module ast did the trick for me
Output:
You can try this:
Not sure if this is the best way to do this, but it gets the job done.
The
coordinate
variable contains a list of two floats which you can use to create yourPolygon
s. Hope this helps!Output: