Convert a JSON struct to a Geometry based on its structure
358732
def fromJson(struct, attributes=None):
    ""
    if isinstance(struct, basestring):
        struct = json.loads(struct)
    indicative_attributes = {
        'x': Point,
        'wkid': SpatialReference,
        'paths': Polyline,
        'rings': Polygon,
        'points': Multipoint,
        'xmin': Envelope
    }
    # bbox string
    if isinstance(struct, basestring) and len(struct.split(',')) == 4:
        return Envelope(*map(float, struct.split(',')))
    # Look for telltale attributes in the dict
    if isinstance(struct, dict):
        for key, cls in indicative_attributes.iteritems():
            if key in struct:
                ret = cls.fromJson(dict((str(key), value)
                                   for (key, value) in struct.iteritems()))
                if attributes:
                    ret.attributes = dict((str(key.lower()), val) 
                                           for (key, val)
                                           in attributes.iteritems())
                return ret
    raise ValueError("Unconvertible to geometry")
857065
@SuppressWarnings("unchecked")
    private static Map<String, String> matdescFromJson(String json) {
        Map<String, String> map = Jackson.fromJsonString(json, Map.class);
        return map == null ? null : Collections.unmodifiableMap(map);
    }
34995
function(geometry) {
            if (geometry == null) {
                return null;
            }
            if (this.internalProjection && this.externalProjection) {
                geometry = geometry.clone();
                geometry.transform(this.internalProjection, 
                                   this.externalProjection);
            }                       
            var geometryType = geometry.CLASS_NAME.split('.')[2];
            var data = this.extract[geometryType.toLowerCase()].apply(this, [geometry]);
            var json;
            if(geometryType == "Collection") {
                json = {
                    "type": "GeometryCollection",
                    "geometries": data
                };
            } else {
                json = {
                    "type": geometryType,
                    "coordinates": data
                };
            }
            
            return json;
        }
232590
def from_json_format(conf):
    ''''''
    if 'fmode' in conf:
        conf['fmode'] = int(conf['fmode'], 8)
    if 'dmode' in conf:
        conf['dmode'] = int(conf['dmode'], 8)
178879
def _get_struct_shapewithstyle(self, shape_number):
        """"""
        obj = _make_object("ShapeWithStyle")
        obj.FillStyles = self._get_struct_fillstylearray(shape_number)
        obj.LineStyles = self._get_struct_linestylearray(shape_number)
        bc = BitConsumer(self._src)
        obj.NumFillBits = n_fill_bits = bc.u_get(4)
        obj.NumlineBits = n_line_bits = bc.u_get(4)
        obj.ShapeRecords = self._get_shaperecords(
            n_fill_bits, n_line_bits, shape_number)
        return obj
1369619
def _parse_geometry(geometry):
        
        if isinstance(geometry, str):
            geometry = shapely.wkt.loads(geometry)
        elif isinstance(geometry, dict):
            geometry = shapely.geometry.shape(geometry)
        elif not isinstance(geometry, shapely.geometry.base.BaseGeometry):
            raise TypeError('Unsupported geometry representation')

        if not isinstance(geometry, (shapely.geometry.Polygon, shapely.geometry.MultiPolygon)):
            raise ValueError('Supported geometry types are polygon and multipolygon, got {}'.format(type(geometry)))

        return geometry
315120
def to_json(self):
        """"""
        return {
            'location': self.location.to_json(),
            'design_days': [des_d.to_json() for des_d in self.design_days]
        }
163245
def _translate_struct(inner_dict):
    """"""
    try:
        optional = inner_dict['optional'].items()
        required = inner_dict['required'].items()
    except KeyError as ex:
        raise DeserializationError("Missing key: {}".format(ex))
    except AttributeError as ex:
        raise DeserializationError(
            "Invalid Structure: {}".format(inner_dict))

    val_dict = {k: _translate(v) for k, v in required}
    val_dict.update({Optional(k): _translate(v) for k, v in optional})
    return val_dict
741059
def from_dict(self, the_dict):
        
        geom = geojson.loads(json.dumps(the_dict))
        result = MultiPolygon([
            [[[0, 0], [0, 0]]],
            [[[1, 1], [1, 1]]]
        ])
        result._geom = geom
        return result
1330497
def from_json(cls, data):
        
        required_keys = ('location', 'design_days')
        for key in required_keys:
            assert key in data, 'Required key "{}" is missing!'.format(key)

        return cls(Location.from_json(data['location']),
                   [DesignDay.from_json(des_day) for des_day in data['design_days']])
452303
def _build_from_geojson(self, src):
        
        geojson = json.loads(self.read(src))
        idx = index.Index()
        data_store = {}
        for i, feature in enumerate(geojson['features']):
            feature = self._build_obj(feature)
            idx.insert(i, feature['geometry'].bounds)
            data_store[i] = feature
        return data_store, idx
1179284
def as_dict(self):
        
        return {"@module": self.__class__.__module__,
                "@class": self.__class__.__name__,
                "coord_geoms": jsanitize(self.coord_geoms)}
1301030
function( json, params, callback ){
    if ( params.geometry ){
      this.geometryFilter( json, params, callback );
    } else if ( params.where ){
      this.whereFilter( json, params, callback );
    } else {
      //probably better to parse all params upfront and confirm valid types
      if ( params.returnCountOnly === 'true' || params.returnCountOnly ){
        
        callback( null, { count: json.features.length });

      } else if ( params.returnIdsOnly === 'true' || params.returnIdsOnly){
        this.getIds( json, params.idField, params, function( err, ids ){
          callback( err, ids );
        });

      } else {

        if (params.orderByFields && params.orderByFields !== ''){
          var fld = params.orderByFields.split(' ');
          var order = params.orderByFields;
          if (fld[fld.length-1] == 'DESC'){
            order = '-' + params.orderByFields;
          }
          json.features = this.orderBy(json.features, params.orderByFields, order);
        }

        if ( ( params.returnGeometry === false || params.returnGeometry == 'false') && (!params.outFields || params.outFields != '*')){
          json.features.forEach(function(f){
            delete f.geometry;
          });
        } else if ( params.outSR && ( params.outSR == '102100' ) ){
          if ( json.spatialReference ){
            json.spatialReference.wkid = params.outSR;
            var coords;
            // project each geometry to merator
            json.features.forEach( function( f ){
              if ( f.geometry.x && f.geometry.y ) {
                coords = new terraformer.Point( [f.geometry.x, f.geometry.y] ).toMercator().coordinates;
                f.geometry.x = coords[0];
                f.geometry.y = coords[1];
              } else if ( f.geometry.rings ){
                f.geometry.rings = new terraformer.Polygon( f.geometry.rings ).toMercator().coordinates;
              } else if ( f.geometry.paths ) {
                f.geometry.paths = new terraformer.LineString( f.geometry.paths ).toMercator().coordinates;
              }
              f.geometry.spatialReference.wkid = params.outSR;
            });
          }
        }

        // checkout for outfields
        if ( params.outFields && params.outFields != '*' ){
          var features = [],
            props,
            outFields = params.outFields.split( ',' );

          json.features.forEach( function( f ){
            props = _.pick(f.attributes || f.properties, outFields);

            var newFeature = { geometry: f.geometry};
            if ( f.properties ) {
              newFeature.properties = props;
            } else {
              newFeature.attributes = props;
            }
            features.push( newFeature );
          });
          json.features = features;
        }

        // before we send back json, process outStats
        if ( params.outStatistics ){
          this.outStatistics( json, params, callback );
        } else {
          callback( null, json );
        }


      }

    }

  }
727529
def build_api_struct(self):
        
        self.clean()
        r = {
            "type": self._type,
            "requested": self._requested,
            "value": self._value
        }
        if self._tags:
            r["tags"] = self._tags

        return r
727177
def structure(self, obj, cl):
        # type: (Any, Type[T]) -> T
        """"""

        return self._structure_func.dispatch(cl)(obj, cl)
402471
def struct_to_dtype(struct):
    """"""
    # str() around name necessary because protobuf gives unicode names, but dtype doesn't
    # support them on Python 2
    fields = [(str(var.name), data_type_to_numpy(var.dataType, var.unsigned))
              for var in struct.vars]
    for s in struct.structs:
        fields.append((str(s.name), struct_to_dtype(s)))

    log.debug('Structure fields: %s', fields)
    dt = np.dtype(fields)
    return dt
455097
def geometry_from_json(obj):
    ''''''
    obj_type = obj.get('type', None)
    if not obj_type:
        return None
    if obj_type == 'FeatureCollection':
        features = obj.get('features', [])
        if len(features):
            obj = obj['features'][0]
            obj_type = obj.get('type', None)
        else:
            return None
    if obj_type == 'Feature':
        geom = obj['geometry']
    else:
        geom = obj
    # @todo we're just assuming it's a geometry at this point
    if 'coordinates' in geom:
        return geom