Generating GeoJSON with Python The Next CEO of Stack OverflowGDAL and Python: How to get coordinates for all cells having a specific value?Looking for GeoJSON describing French departments?Geometry workflow from Shapely to GeoJSONWhere to find GeoJSON data for the UK?Writing geoJson from rasterstatsConverting shapes in a personal geodatabase to GeoJSONHow to import DGN geometry into a file geodatabase?OGR CreateLayer returns TypeErrorAdd joined data in fiona with new schemaFilter geojson or shapefilesWhy is feature.geometry() None in my user-defined expression function?How to correctly import GeoJSON in PostGIS?Obtaining shape or width of road in GeoJSON format?Using SET methods when feature classes setup in GDB using python, comtypes, ArcObjects?Getting polygons out of multi-polygon GeoJSON files?Set or change the geometry type of an empty point shapefile using Python with GDAL/OGR

Reference request: Grassmannian and Plucker coordinates in type B, C, D

Easy to read palindrome checker

Help/tips for a first time writer?

Inexact numbers as keys in Association?

Is there an equivalent of cd - for cp or mv

Is it professional to write unrelated content in an almost-empty email?

Physiological effects of huge anime eyes

Would a grinding machine be a simple and workable propulsion system for an interplanetary spacecraft?

Example of a Mathematician/Physicist whose Other Publications during their PhD eclipsed their PhD Thesis

Can I board the first leg of the flight without having final country's visa?

Why doesn't UK go for the same deal Japan has with EU to resolve Brexit?

Getting Stale Gas Out of a Gas Tank w/out Dropping the Tank

How many extra stops do monopods offer for tele photographs?

Can I use the word “Senior” as part of a job title directly in German?

Defamation due to breach of confidentiality

"Eavesdropping" vs "Listen in on"

0-rank tensor vs vector in 1D

How to properly draw diagonal line while using multicolumn inside tabular environment?

If Nick Fury and Coulson already knew about aliens (Kree and Skrull) why did they wait until Thor's appearance to start making weapons?

Help understanding this unsettling image of Titan, Epimetheus, and Saturn's rings?

What does "shotgun unity" refer to here in this sentence?

Regression vs Random Forest - Combination of features

Is it ever safe to open a suspicious HTML file (e.g. email attachment)?

Is it convenient to ask the journal's editor for two additional days to complete a review?



Generating GeoJSON with Python



The Next CEO of Stack OverflowGDAL and Python: How to get coordinates for all cells having a specific value?Looking for GeoJSON describing French departments?Geometry workflow from Shapely to GeoJSONWhere to find GeoJSON data for the UK?Writing geoJson from rasterstatsConverting shapes in a personal geodatabase to GeoJSONHow to import DGN geometry into a file geodatabase?OGR CreateLayer returns TypeErrorAdd joined data in fiona with new schemaFilter geojson or shapefilesWhy is feature.geometry() None in my user-defined expression function?How to correctly import GeoJSON in PostGIS?Obtaining shape or width of road in GeoJSON format?Using SET methods when feature classes setup in GDB using python, comtypes, ArcObjects?Getting polygons out of multi-polygon GeoJSON files?Set or change the geometry type of an empty point shapefile using Python with GDAL/OGR










16















I want to programmatically create a GeoJSON file using polygons from a shapefile but adding attributes from my own application.



This is easily done for a shapefile:



def create_data_dayer(self,varlist, data):
"""
Creates a new shape to contain data about nodes.
varlist is the list of fields names associated with
the nodes.
data is a list of lists whose first element is the geocode
and the remaining elements are values of the fields, in the
same order as they appear in varlist.
"""
if os.path.exists(os.path.join(self.outdir,'Data.shp')):
os.remove(os.path.join(self.outdir,'Data.shp'))
os.remove(os.path.join(self.outdir,'Data.shx'))
os.remove(os.path.join(self.outdir,'Data.dbf'))
# Creates a new shape file to hold the data
if not self.datasource:
dsd = self.driver.CreateDataSource(os.path.join(self.outdir,'Data.shp'))
self.datasource = dsd
dl = dsd.CreateLayer("sim_results",geom_type=ogr.wkbPolygon)
#Create the fields
fi1 = ogr.FieldDefn("geocode",field_type=ogr.OFTInteger)
dl.CreateField(fi1)
for v in varlist:
#print "creating data fields"
fi = ogr.FieldDefn(v,field_type=ogr.OFTString)
fi.SetPrecision(12)
dl.CreateField(fi)

#Add the features (points)
for n,l in enumerate(data):
#Iterate over the lines of the data matrix.
gc = l[0]
try:
geom = self.geomdict[gc]
if geom.GetGeometryType() != 3: continue
#print geom.GetGeometryCount()
fe = ogr.Feature(dl.GetLayerDefn())
fe.SetField('geocode',gc)
for v,d in zip (varlist,l[1:]):
#print v,d
fe.SetField(v,str(d))
#Add the geometry
#print "cloning geometry"
clone = geom.Clone()
#print geom
#print "setting geometry"
fe.SetGeometry(clone)
#print "creating geom"
dl.CreateFeature(fe)
except: #Geocode not in polygon dictionary
pass
dl.SyncToDisk()


since I have all the geometries on a dictionary by geocode (self.geomdict) I simply create the features, set the fields and clone the geometries from pre-existing layer (code loading that layer omitted for simplicity). All I need now is a way to generate the GeoJSON from the combination of fields and geometries, naturally with the help of OGR to get the rest of the file right (CRS, etc. as from the source map)



How do export the feature collection generated as above?










share|improve this question




























    16















    I want to programmatically create a GeoJSON file using polygons from a shapefile but adding attributes from my own application.



    This is easily done for a shapefile:



    def create_data_dayer(self,varlist, data):
    """
    Creates a new shape to contain data about nodes.
    varlist is the list of fields names associated with
    the nodes.
    data is a list of lists whose first element is the geocode
    and the remaining elements are values of the fields, in the
    same order as they appear in varlist.
    """
    if os.path.exists(os.path.join(self.outdir,'Data.shp')):
    os.remove(os.path.join(self.outdir,'Data.shp'))
    os.remove(os.path.join(self.outdir,'Data.shx'))
    os.remove(os.path.join(self.outdir,'Data.dbf'))
    # Creates a new shape file to hold the data
    if not self.datasource:
    dsd = self.driver.CreateDataSource(os.path.join(self.outdir,'Data.shp'))
    self.datasource = dsd
    dl = dsd.CreateLayer("sim_results",geom_type=ogr.wkbPolygon)
    #Create the fields
    fi1 = ogr.FieldDefn("geocode",field_type=ogr.OFTInteger)
    dl.CreateField(fi1)
    for v in varlist:
    #print "creating data fields"
    fi = ogr.FieldDefn(v,field_type=ogr.OFTString)
    fi.SetPrecision(12)
    dl.CreateField(fi)

    #Add the features (points)
    for n,l in enumerate(data):
    #Iterate over the lines of the data matrix.
    gc = l[0]
    try:
    geom = self.geomdict[gc]
    if geom.GetGeometryType() != 3: continue
    #print geom.GetGeometryCount()
    fe = ogr.Feature(dl.GetLayerDefn())
    fe.SetField('geocode',gc)
    for v,d in zip (varlist,l[1:]):
    #print v,d
    fe.SetField(v,str(d))
    #Add the geometry
    #print "cloning geometry"
    clone = geom.Clone()
    #print geom
    #print "setting geometry"
    fe.SetGeometry(clone)
    #print "creating geom"
    dl.CreateFeature(fe)
    except: #Geocode not in polygon dictionary
    pass
    dl.SyncToDisk()


    since I have all the geometries on a dictionary by geocode (self.geomdict) I simply create the features, set the fields and clone the geometries from pre-existing layer (code loading that layer omitted for simplicity). All I need now is a way to generate the GeoJSON from the combination of fields and geometries, naturally with the help of OGR to get the rest of the file right (CRS, etc. as from the source map)



    How do export the feature collection generated as above?










    share|improve this question


























      16












      16








      16


      10






      I want to programmatically create a GeoJSON file using polygons from a shapefile but adding attributes from my own application.



      This is easily done for a shapefile:



      def create_data_dayer(self,varlist, data):
      """
      Creates a new shape to contain data about nodes.
      varlist is the list of fields names associated with
      the nodes.
      data is a list of lists whose first element is the geocode
      and the remaining elements are values of the fields, in the
      same order as they appear in varlist.
      """
      if os.path.exists(os.path.join(self.outdir,'Data.shp')):
      os.remove(os.path.join(self.outdir,'Data.shp'))
      os.remove(os.path.join(self.outdir,'Data.shx'))
      os.remove(os.path.join(self.outdir,'Data.dbf'))
      # Creates a new shape file to hold the data
      if not self.datasource:
      dsd = self.driver.CreateDataSource(os.path.join(self.outdir,'Data.shp'))
      self.datasource = dsd
      dl = dsd.CreateLayer("sim_results",geom_type=ogr.wkbPolygon)
      #Create the fields
      fi1 = ogr.FieldDefn("geocode",field_type=ogr.OFTInteger)
      dl.CreateField(fi1)
      for v in varlist:
      #print "creating data fields"
      fi = ogr.FieldDefn(v,field_type=ogr.OFTString)
      fi.SetPrecision(12)
      dl.CreateField(fi)

      #Add the features (points)
      for n,l in enumerate(data):
      #Iterate over the lines of the data matrix.
      gc = l[0]
      try:
      geom = self.geomdict[gc]
      if geom.GetGeometryType() != 3: continue
      #print geom.GetGeometryCount()
      fe = ogr.Feature(dl.GetLayerDefn())
      fe.SetField('geocode',gc)
      for v,d in zip (varlist,l[1:]):
      #print v,d
      fe.SetField(v,str(d))
      #Add the geometry
      #print "cloning geometry"
      clone = geom.Clone()
      #print geom
      #print "setting geometry"
      fe.SetGeometry(clone)
      #print "creating geom"
      dl.CreateFeature(fe)
      except: #Geocode not in polygon dictionary
      pass
      dl.SyncToDisk()


      since I have all the geometries on a dictionary by geocode (self.geomdict) I simply create the features, set the fields and clone the geometries from pre-existing layer (code loading that layer omitted for simplicity). All I need now is a way to generate the GeoJSON from the combination of fields and geometries, naturally with the help of OGR to get the rest of the file right (CRS, etc. as from the source map)



      How do export the feature collection generated as above?










      share|improve this question
















      I want to programmatically create a GeoJSON file using polygons from a shapefile but adding attributes from my own application.



      This is easily done for a shapefile:



      def create_data_dayer(self,varlist, data):
      """
      Creates a new shape to contain data about nodes.
      varlist is the list of fields names associated with
      the nodes.
      data is a list of lists whose first element is the geocode
      and the remaining elements are values of the fields, in the
      same order as they appear in varlist.
      """
      if os.path.exists(os.path.join(self.outdir,'Data.shp')):
      os.remove(os.path.join(self.outdir,'Data.shp'))
      os.remove(os.path.join(self.outdir,'Data.shx'))
      os.remove(os.path.join(self.outdir,'Data.dbf'))
      # Creates a new shape file to hold the data
      if not self.datasource:
      dsd = self.driver.CreateDataSource(os.path.join(self.outdir,'Data.shp'))
      self.datasource = dsd
      dl = dsd.CreateLayer("sim_results",geom_type=ogr.wkbPolygon)
      #Create the fields
      fi1 = ogr.FieldDefn("geocode",field_type=ogr.OFTInteger)
      dl.CreateField(fi1)
      for v in varlist:
      #print "creating data fields"
      fi = ogr.FieldDefn(v,field_type=ogr.OFTString)
      fi.SetPrecision(12)
      dl.CreateField(fi)

      #Add the features (points)
      for n,l in enumerate(data):
      #Iterate over the lines of the data matrix.
      gc = l[0]
      try:
      geom = self.geomdict[gc]
      if geom.GetGeometryType() != 3: continue
      #print geom.GetGeometryCount()
      fe = ogr.Feature(dl.GetLayerDefn())
      fe.SetField('geocode',gc)
      for v,d in zip (varlist,l[1:]):
      #print v,d
      fe.SetField(v,str(d))
      #Add the geometry
      #print "cloning geometry"
      clone = geom.Clone()
      #print geom
      #print "setting geometry"
      fe.SetGeometry(clone)
      #print "creating geom"
      dl.CreateFeature(fe)
      except: #Geocode not in polygon dictionary
      pass
      dl.SyncToDisk()


      since I have all the geometries on a dictionary by geocode (self.geomdict) I simply create the features, set the fields and clone the geometries from pre-existing layer (code loading that layer omitted for simplicity). All I need now is a way to generate the GeoJSON from the combination of fields and geometries, naturally with the help of OGR to get the rest of the file right (CRS, etc. as from the source map)



      How do export the feature collection generated as above?







      python geojson ogr fiona






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Aug 3 '17 at 1:30









      PolyGeo

      53.8k1781245




      53.8k1781245










      asked Nov 19 '12 at 9:30









      fccoelhofccoelho

      4902719




      4902719




















          3 Answers
          3






          active

          oldest

          votes


















          14














          Happily OGR can do this for you as both ogr.Feature and ogr.Geometry objects have ExportToJson() methods. In your code;



          fe.ExportToJson()



          And since geojson FeatureCollection objects are simply dictionaries with a type of FeatureCollection and a features object containing a list of Feature objects.



          feature_collection = "type": "FeatureCollection",
          "features": []


          feature_collection["features"].append(fe.ExportToJson())


          The CRS object in a feature collection can be one of two types:



          • A named CRS (e.g. an OGC URN or an EPSG code)

          • A link object with a URI and a type such as "proj4"

          Depending on your data format it's quite likely that the name is going to be a pain to get from OGR. Instead if we write the projection to a file on disk which we can reference with the URI. We can grab the projection from the layer object (which has several Export functions)



          spatial_reference = dl.GetSpatialRef()

          with open("data.crs", "wb") as f:
          f.write(spatial_reference.ExportToProj4())

          feature_collection["crs"] = "type": "link",
          "properties":
          "href": "data.crs",
          "type": "proj4"







          share|improve this answer























          • This is a good solution, because it doesn't add an extra dependency to my project like the (nice) solution of @sgillies

            – fccoelho
            Nov 22 '12 at 15:42











          • I jus finished my testing with this solution and it worked nicely. However I had to handle manually when features had unicode characters in field names, since ogr.py didn't handle them properly.

            – fccoelho
            Nov 24 '12 at 21:35











          • I don't know if functionality has changed since, but fe.ExportToJson() returns a string, so you need to wrap in with json.loads(...). Otherwise, this is super helpful!

            – jon_two
            May 4 '18 at 16:44


















          33














          If you've got an GDAL/OGR dev environment (headers, libs), you could radically simplify your code by using Fiona. To read features from a shapefile, add new attributes, and write them out as GeoJSON is just a handful of lines:



          import fiona
          import json

          features = []
          crs = None
          with fiona.collection("docs/data/test_uk.shp", "r") as source:
          for feat in source:
          feat['properties'].update(...) # with your attributes
          features.append(feat)
          crs = " ".join("+%s=%s" % (k,v) for k,v in source.crs.items())

          my_layer =
          "type": "FeatureCollection",
          "features": features,
          "crs":
          "type": "link",
          "properties": "href": "my_layer.crs", "type": "proj4"

          with open("my_layer.json", "w") as f:
          f.write(json.dumps(my_layer))
          with open("my_layer.crs", "w") as f:
          f.write(crs)





          share|improve this answer


















          • 4





            Fiona docs are killer!

            – Chad Cooper
            Nov 20 '12 at 16:40











          • Would vote up more than once if I could!

            – om_henners
            Nov 20 '12 at 23:26











          • Isn't there a way to include the crs definition in GeoJSON?

            – fccoelho
            Nov 22 '12 at 15:41


















          0














          This is the simplest and easiest one in Fiona. you can set the SRS for output GeoJSON.



          import fiona
          from fiona.crs import from_epsg

          source= fiona.open('shp/second_shp.shp', 'r', encoding = 'utf-8')

          with fiona.open('tool_shp_geojson/geojson_fiona.json','w', driver ="GeoJSON", schema=source.schema, encoding = 'utf-8', crs=fiona.crs.from_epsg(4326)) as geojson:
          geojson.write(feat)





          share|improve this answer























            Your Answer








            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "79"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: false,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: null,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fgis.stackexchange.com%2fquestions%2f41465%2fgenerating-geojson-with-python%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            3 Answers
            3






            active

            oldest

            votes








            3 Answers
            3






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            14














            Happily OGR can do this for you as both ogr.Feature and ogr.Geometry objects have ExportToJson() methods. In your code;



            fe.ExportToJson()



            And since geojson FeatureCollection objects are simply dictionaries with a type of FeatureCollection and a features object containing a list of Feature objects.



            feature_collection = "type": "FeatureCollection",
            "features": []


            feature_collection["features"].append(fe.ExportToJson())


            The CRS object in a feature collection can be one of two types:



            • A named CRS (e.g. an OGC URN or an EPSG code)

            • A link object with a URI and a type such as "proj4"

            Depending on your data format it's quite likely that the name is going to be a pain to get from OGR. Instead if we write the projection to a file on disk which we can reference with the URI. We can grab the projection from the layer object (which has several Export functions)



            spatial_reference = dl.GetSpatialRef()

            with open("data.crs", "wb") as f:
            f.write(spatial_reference.ExportToProj4())

            feature_collection["crs"] = "type": "link",
            "properties":
            "href": "data.crs",
            "type": "proj4"







            share|improve this answer























            • This is a good solution, because it doesn't add an extra dependency to my project like the (nice) solution of @sgillies

              – fccoelho
              Nov 22 '12 at 15:42











            • I jus finished my testing with this solution and it worked nicely. However I had to handle manually when features had unicode characters in field names, since ogr.py didn't handle them properly.

              – fccoelho
              Nov 24 '12 at 21:35











            • I don't know if functionality has changed since, but fe.ExportToJson() returns a string, so you need to wrap in with json.loads(...). Otherwise, this is super helpful!

              – jon_two
              May 4 '18 at 16:44















            14














            Happily OGR can do this for you as both ogr.Feature and ogr.Geometry objects have ExportToJson() methods. In your code;



            fe.ExportToJson()



            And since geojson FeatureCollection objects are simply dictionaries with a type of FeatureCollection and a features object containing a list of Feature objects.



            feature_collection = "type": "FeatureCollection",
            "features": []


            feature_collection["features"].append(fe.ExportToJson())


            The CRS object in a feature collection can be one of two types:



            • A named CRS (e.g. an OGC URN or an EPSG code)

            • A link object with a URI and a type such as "proj4"

            Depending on your data format it's quite likely that the name is going to be a pain to get from OGR. Instead if we write the projection to a file on disk which we can reference with the URI. We can grab the projection from the layer object (which has several Export functions)



            spatial_reference = dl.GetSpatialRef()

            with open("data.crs", "wb") as f:
            f.write(spatial_reference.ExportToProj4())

            feature_collection["crs"] = "type": "link",
            "properties":
            "href": "data.crs",
            "type": "proj4"







            share|improve this answer























            • This is a good solution, because it doesn't add an extra dependency to my project like the (nice) solution of @sgillies

              – fccoelho
              Nov 22 '12 at 15:42











            • I jus finished my testing with this solution and it worked nicely. However I had to handle manually when features had unicode characters in field names, since ogr.py didn't handle them properly.

              – fccoelho
              Nov 24 '12 at 21:35











            • I don't know if functionality has changed since, but fe.ExportToJson() returns a string, so you need to wrap in with json.loads(...). Otherwise, this is super helpful!

              – jon_two
              May 4 '18 at 16:44













            14












            14








            14







            Happily OGR can do this for you as both ogr.Feature and ogr.Geometry objects have ExportToJson() methods. In your code;



            fe.ExportToJson()



            And since geojson FeatureCollection objects are simply dictionaries with a type of FeatureCollection and a features object containing a list of Feature objects.



            feature_collection = "type": "FeatureCollection",
            "features": []


            feature_collection["features"].append(fe.ExportToJson())


            The CRS object in a feature collection can be one of two types:



            • A named CRS (e.g. an OGC URN or an EPSG code)

            • A link object with a URI and a type such as "proj4"

            Depending on your data format it's quite likely that the name is going to be a pain to get from OGR. Instead if we write the projection to a file on disk which we can reference with the URI. We can grab the projection from the layer object (which has several Export functions)



            spatial_reference = dl.GetSpatialRef()

            with open("data.crs", "wb") as f:
            f.write(spatial_reference.ExportToProj4())

            feature_collection["crs"] = "type": "link",
            "properties":
            "href": "data.crs",
            "type": "proj4"







            share|improve this answer













            Happily OGR can do this for you as both ogr.Feature and ogr.Geometry objects have ExportToJson() methods. In your code;



            fe.ExportToJson()



            And since geojson FeatureCollection objects are simply dictionaries with a type of FeatureCollection and a features object containing a list of Feature objects.



            feature_collection = "type": "FeatureCollection",
            "features": []


            feature_collection["features"].append(fe.ExportToJson())


            The CRS object in a feature collection can be one of two types:



            • A named CRS (e.g. an OGC URN or an EPSG code)

            • A link object with a URI and a type such as "proj4"

            Depending on your data format it's quite likely that the name is going to be a pain to get from OGR. Instead if we write the projection to a file on disk which we can reference with the URI. We can grab the projection from the layer object (which has several Export functions)



            spatial_reference = dl.GetSpatialRef()

            with open("data.crs", "wb") as f:
            f.write(spatial_reference.ExportToProj4())

            feature_collection["crs"] = "type": "link",
            "properties":
            "href": "data.crs",
            "type": "proj4"








            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 19 '12 at 10:32









            om_hennersom_henners

            13.4k23375




            13.4k23375












            • This is a good solution, because it doesn't add an extra dependency to my project like the (nice) solution of @sgillies

              – fccoelho
              Nov 22 '12 at 15:42











            • I jus finished my testing with this solution and it worked nicely. However I had to handle manually when features had unicode characters in field names, since ogr.py didn't handle them properly.

              – fccoelho
              Nov 24 '12 at 21:35











            • I don't know if functionality has changed since, but fe.ExportToJson() returns a string, so you need to wrap in with json.loads(...). Otherwise, this is super helpful!

              – jon_two
              May 4 '18 at 16:44

















            • This is a good solution, because it doesn't add an extra dependency to my project like the (nice) solution of @sgillies

              – fccoelho
              Nov 22 '12 at 15:42











            • I jus finished my testing with this solution and it worked nicely. However I had to handle manually when features had unicode characters in field names, since ogr.py didn't handle them properly.

              – fccoelho
              Nov 24 '12 at 21:35











            • I don't know if functionality has changed since, but fe.ExportToJson() returns a string, so you need to wrap in with json.loads(...). Otherwise, this is super helpful!

              – jon_two
              May 4 '18 at 16:44
















            This is a good solution, because it doesn't add an extra dependency to my project like the (nice) solution of @sgillies

            – fccoelho
            Nov 22 '12 at 15:42





            This is a good solution, because it doesn't add an extra dependency to my project like the (nice) solution of @sgillies

            – fccoelho
            Nov 22 '12 at 15:42













            I jus finished my testing with this solution and it worked nicely. However I had to handle manually when features had unicode characters in field names, since ogr.py didn't handle them properly.

            – fccoelho
            Nov 24 '12 at 21:35





            I jus finished my testing with this solution and it worked nicely. However I had to handle manually when features had unicode characters in field names, since ogr.py didn't handle them properly.

            – fccoelho
            Nov 24 '12 at 21:35













            I don't know if functionality has changed since, but fe.ExportToJson() returns a string, so you need to wrap in with json.loads(...). Otherwise, this is super helpful!

            – jon_two
            May 4 '18 at 16:44





            I don't know if functionality has changed since, but fe.ExportToJson() returns a string, so you need to wrap in with json.loads(...). Otherwise, this is super helpful!

            – jon_two
            May 4 '18 at 16:44













            33














            If you've got an GDAL/OGR dev environment (headers, libs), you could radically simplify your code by using Fiona. To read features from a shapefile, add new attributes, and write them out as GeoJSON is just a handful of lines:



            import fiona
            import json

            features = []
            crs = None
            with fiona.collection("docs/data/test_uk.shp", "r") as source:
            for feat in source:
            feat['properties'].update(...) # with your attributes
            features.append(feat)
            crs = " ".join("+%s=%s" % (k,v) for k,v in source.crs.items())

            my_layer =
            "type": "FeatureCollection",
            "features": features,
            "crs":
            "type": "link",
            "properties": "href": "my_layer.crs", "type": "proj4"

            with open("my_layer.json", "w") as f:
            f.write(json.dumps(my_layer))
            with open("my_layer.crs", "w") as f:
            f.write(crs)





            share|improve this answer


















            • 4





              Fiona docs are killer!

              – Chad Cooper
              Nov 20 '12 at 16:40











            • Would vote up more than once if I could!

              – om_henners
              Nov 20 '12 at 23:26











            • Isn't there a way to include the crs definition in GeoJSON?

              – fccoelho
              Nov 22 '12 at 15:41















            33














            If you've got an GDAL/OGR dev environment (headers, libs), you could radically simplify your code by using Fiona. To read features from a shapefile, add new attributes, and write them out as GeoJSON is just a handful of lines:



            import fiona
            import json

            features = []
            crs = None
            with fiona.collection("docs/data/test_uk.shp", "r") as source:
            for feat in source:
            feat['properties'].update(...) # with your attributes
            features.append(feat)
            crs = " ".join("+%s=%s" % (k,v) for k,v in source.crs.items())

            my_layer =
            "type": "FeatureCollection",
            "features": features,
            "crs":
            "type": "link",
            "properties": "href": "my_layer.crs", "type": "proj4"

            with open("my_layer.json", "w") as f:
            f.write(json.dumps(my_layer))
            with open("my_layer.crs", "w") as f:
            f.write(crs)





            share|improve this answer


















            • 4





              Fiona docs are killer!

              – Chad Cooper
              Nov 20 '12 at 16:40











            • Would vote up more than once if I could!

              – om_henners
              Nov 20 '12 at 23:26











            • Isn't there a way to include the crs definition in GeoJSON?

              – fccoelho
              Nov 22 '12 at 15:41













            33












            33








            33







            If you've got an GDAL/OGR dev environment (headers, libs), you could radically simplify your code by using Fiona. To read features from a shapefile, add new attributes, and write them out as GeoJSON is just a handful of lines:



            import fiona
            import json

            features = []
            crs = None
            with fiona.collection("docs/data/test_uk.shp", "r") as source:
            for feat in source:
            feat['properties'].update(...) # with your attributes
            features.append(feat)
            crs = " ".join("+%s=%s" % (k,v) for k,v in source.crs.items())

            my_layer =
            "type": "FeatureCollection",
            "features": features,
            "crs":
            "type": "link",
            "properties": "href": "my_layer.crs", "type": "proj4"

            with open("my_layer.json", "w") as f:
            f.write(json.dumps(my_layer))
            with open("my_layer.crs", "w") as f:
            f.write(crs)





            share|improve this answer













            If you've got an GDAL/OGR dev environment (headers, libs), you could radically simplify your code by using Fiona. To read features from a shapefile, add new attributes, and write them out as GeoJSON is just a handful of lines:



            import fiona
            import json

            features = []
            crs = None
            with fiona.collection("docs/data/test_uk.shp", "r") as source:
            for feat in source:
            feat['properties'].update(...) # with your attributes
            features.append(feat)
            crs = " ".join("+%s=%s" % (k,v) for k,v in source.crs.items())

            my_layer =
            "type": "FeatureCollection",
            "features": features,
            "crs":
            "type": "link",
            "properties": "href": "my_layer.crs", "type": "proj4"

            with open("my_layer.json", "w") as f:
            f.write(json.dumps(my_layer))
            with open("my_layer.crs", "w") as f:
            f.write(crs)






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 20 '12 at 16:22









            sgilliessgillies

            6,79312023




            6,79312023







            • 4





              Fiona docs are killer!

              – Chad Cooper
              Nov 20 '12 at 16:40











            • Would vote up more than once if I could!

              – om_henners
              Nov 20 '12 at 23:26











            • Isn't there a way to include the crs definition in GeoJSON?

              – fccoelho
              Nov 22 '12 at 15:41












            • 4





              Fiona docs are killer!

              – Chad Cooper
              Nov 20 '12 at 16:40











            • Would vote up more than once if I could!

              – om_henners
              Nov 20 '12 at 23:26











            • Isn't there a way to include the crs definition in GeoJSON?

              – fccoelho
              Nov 22 '12 at 15:41







            4




            4





            Fiona docs are killer!

            – Chad Cooper
            Nov 20 '12 at 16:40





            Fiona docs are killer!

            – Chad Cooper
            Nov 20 '12 at 16:40













            Would vote up more than once if I could!

            – om_henners
            Nov 20 '12 at 23:26





            Would vote up more than once if I could!

            – om_henners
            Nov 20 '12 at 23:26













            Isn't there a way to include the crs definition in GeoJSON?

            – fccoelho
            Nov 22 '12 at 15:41





            Isn't there a way to include the crs definition in GeoJSON?

            – fccoelho
            Nov 22 '12 at 15:41











            0














            This is the simplest and easiest one in Fiona. you can set the SRS for output GeoJSON.



            import fiona
            from fiona.crs import from_epsg

            source= fiona.open('shp/second_shp.shp', 'r', encoding = 'utf-8')

            with fiona.open('tool_shp_geojson/geojson_fiona.json','w', driver ="GeoJSON", schema=source.schema, encoding = 'utf-8', crs=fiona.crs.from_epsg(4326)) as geojson:
            geojson.write(feat)





            share|improve this answer



























              0














              This is the simplest and easiest one in Fiona. you can set the SRS for output GeoJSON.



              import fiona
              from fiona.crs import from_epsg

              source= fiona.open('shp/second_shp.shp', 'r', encoding = 'utf-8')

              with fiona.open('tool_shp_geojson/geojson_fiona.json','w', driver ="GeoJSON", schema=source.schema, encoding = 'utf-8', crs=fiona.crs.from_epsg(4326)) as geojson:
              geojson.write(feat)





              share|improve this answer

























                0












                0








                0







                This is the simplest and easiest one in Fiona. you can set the SRS for output GeoJSON.



                import fiona
                from fiona.crs import from_epsg

                source= fiona.open('shp/second_shp.shp', 'r', encoding = 'utf-8')

                with fiona.open('tool_shp_geojson/geojson_fiona.json','w', driver ="GeoJSON", schema=source.schema, encoding = 'utf-8', crs=fiona.crs.from_epsg(4326)) as geojson:
                geojson.write(feat)





                share|improve this answer













                This is the simplest and easiest one in Fiona. you can set the SRS for output GeoJSON.



                import fiona
                from fiona.crs import from_epsg

                source= fiona.open('shp/second_shp.shp', 'r', encoding = 'utf-8')

                with fiona.open('tool_shp_geojson/geojson_fiona.json','w', driver ="GeoJSON", schema=source.schema, encoding = 'utf-8', crs=fiona.crs.from_epsg(4326)) as geojson:
                geojson.write(feat)






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered 2 days ago









                Muhammad Imran SiddiqueMuhammad Imran Siddique

                1508




                1508



























                    draft saved

                    draft discarded
















































                    Thanks for contributing an answer to Geographic Information Systems Stack Exchange!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid


                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.

                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fgis.stackexchange.com%2fquestions%2f41465%2fgenerating-geojson-with-python%23new-answer', 'question_page');

                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Romeo and Juliet ContentsCharactersSynopsisSourcesDate and textThemes and motifsCriticism and interpretationLegacyScene by sceneSee alsoNotes and referencesSourcesExternal linksNavigation menu"Consumer Price Index (estimate) 1800–"10.2307/28710160037-3222287101610.1093/res/II.5.31910.2307/45967845967810.2307/2869925286992510.1525/jams.1982.35.3.03a00050"Dada Masilo: South African dancer who breaks the rules"10.1093/res/os-XV.57.1610.2307/28680942868094"Sweet Sorrow: Mann-Korman's Romeo and Juliet Closes Sept. 5 at MN's Ordway"the original10.2307/45957745957710.1017/CCOL0521570476.009"Ram Leela box office collections hit massive Rs 100 crore, pulverises prediction"Archived"Broadway Revival of Romeo and Juliet, Starring Orlando Bloom and Condola Rashad, Will Close Dec. 8"Archived10.1075/jhp.7.1.04hon"Wherefore art thou, Romeo? To make us laugh at Navy Pier"the original10.1093/gmo/9781561592630.article.O006772"Ram-leela Review Roundup: Critics Hail Film as Best Adaptation of Romeo and Juliet"Archived10.2307/31946310047-77293194631"Romeo and Juliet get Twitter treatment""Juliet's Nurse by Lois Leveen""Romeo and Juliet: Orlando Bloom's Broadway Debut Released in Theaters for Valentine's Day"Archived"Romeo and Juliet Has No Balcony"10.1093/gmo/9781561592630.article.O00778110.2307/2867423286742310.1076/enst.82.2.115.959510.1080/00138380601042675"A plague o' both your houses: error in GCSE exam paper forces apology""Juliet of the Five O'Clock Shadow, and Other Wonders"10.2307/33912430027-4321339124310.2307/28487440038-7134284874410.2307/29123140149-661129123144728341M"Weekender Guide: Shakespeare on The Drive""balcony"UK public library membership"romeo"UK public library membership10.1017/CCOL9780521844291"Post-Zionist Critique on Israel and the Palestinians Part III: Popular Culture"10.2307/25379071533-86140377-919X2537907"Capulets and Montagues: UK exam board admit mixing names up in Romeo and Juliet paper"Istoria Novellamente Ritrovata di Due Nobili Amanti2027/mdp.390150822329610820-750X"GCSE exam error: Board accidentally rewrites Shakespeare"10.2307/29176390149-66112917639"Exam board apologises after error in English GCSE paper which confused characters in Shakespeare's Romeo and Juliet""From Mariotto and Ganozza to Romeo and Guilietta: Metamorphoses of a Renaissance Tale"10.2307/37323537323510.2307/2867455286745510.2307/28678912867891"10 Questions for Taylor Swift"10.2307/28680922868092"Haymarket Theatre""The Zeffirelli Way: Revealing Talk by Florentine Director""Michael Smuin: 1938-2007 / Prolific dance director had showy career"The Life and Art of Edwin BoothRomeo and JulietRomeo and JulietRomeo and JulietRomeo and JulietEasy Read Romeo and JulietRomeo and Julieteeecb12003684p(data)4099369-3n8211610759dbe00d-a9e2-41a3-b2c1-977dd692899302814385X313670221313670221

                    Creating closest line along the point''s azimuth using PostgreSQL Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) Announcing the arrival of Valued Associate #679: Cesar Manara Unicorn Meta Zoo #1: Why another podcast?Drawing line between points at specific distance in PostGIS?How to efficiently find the closest point over the dateline?How to find the nearest point by using PostGIS function?PostGIS nearest point with LATERAL JOIN in PostgreSQL 9.3+Creating a table and inserting selected streets using plpgsql functionsCreating a table that stores Distances and other columnSaving select query results (year wise) from PostgreSQL/PostGIS to text filesWhat is the information behind this geometry?How to give start and end vertex ids dynamically in pgr_dijkstra?Point to Polygon nearest distance DS_distance is not using geography index & knn <-> or <#> does not give result in orderLine to point conversion with start point and end point detection?

                    Crop image to path created in TikZ? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)Crop an inserted image?TikZ pictures does not appear in posterImage behind and beyond crop marks?Tikz picture as large as possible on A4 PageTransparency vs image compression dilemmaHow to crop background from image automatically?Image does not cropTikzexternal capturing crop marks when externalizing pgfplots?How to include image path that contains a dollar signCrop image with left size given