Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from pprint import pprint
- from typing import Any, Dict, List
- from marshmallow import Schema, fields, ValidationError, post_load
- RAW = '''{
- "id": "LC81770382018108LGN00",
- "geometry": {
- "type": "Polygon",
- "coordinates": [
- [
- [
- 30.024526874451784,
- 32.78682209753362
- ],
- [
- 31.957976470246887,
- 32.41139662622062
- ],
- [
- 31.477118543417134,
- 30.686648489399253
- ],
- [
- 29.57999924553097,
- 31.061660146074402
- ],
- [
- 30.024526874451784,
- 32.78682209753362
- ]
- ]
- ]
- },
- "properties": {
- "acquired_on": "2018-04-18T08:28:55.492251Z",
- "cloud_cover": 0.014,
- "resolution": 30,
- "wrs_path": "177",
- "wrs_row": "038"
- },
- "type": "Feature"
- }'''
- class Feature:
- class Geometry:
- def __init__(self, type: str, coordinates: List[Any]):
- self.type = type
- self.coordinates = coordinates
- def __init__(self, id: str, geometry: Geometry, properties: Dict[str, Any], type: str = 'Feature'):
- self.geometry = geometry
- self.id = id
- self.properties = properties
- self.type = type
- class FeatureSchema(Schema):
- class GeometrySchema(Schema):
- type = fields.Str()
- coordinates = fields.List(fields.Field())
- @post_load
- def instantiate(self, data):
- return Feature.Geometry(**data)
- id = fields.Str()
- type = fields.Constant('Feature')
- geometry = fields.Nested(GeometrySchema)
- properties = fields.Dict()
- @post_load
- def instantiate(self, data: Dict):
- data.pop('type')
- return Feature(**data)
- try:
- feature: Feature = FeatureSchema(strict=True).loads(RAW).data
- print(feature)
- except ValidationError as err:
- print('error:', err)
- exit(1)
Add Comment
Please, Sign In to add comment