[GIS] Help with manipulating JSON to geoJSON

geojsonpython

So i"m basically getting this JSON returned from a REST call (I'm using Python).

[
  {
    "ipAddress": "X.X.X.X",
    "score": "1000",

  }
]

I want to convert this to geoJSON so I can plot the data on a leaflet map. So I plan to send this object off to freegeoip.net and get the latitude / longitude data.

But how do I convert this to geoJSON after while retaining the ip address and score data? Is there a library or something that I can use for this purpose? Any ideas would be great.

Best Answer

What you need is to convert your data to a GeoJSON Feature or FeatureCollection. The GeoJSON geometries, Point, Polygon, MultiPolygon, et cetera, don't support attributes like ipAddress and score, in your case. You need to define a Feature which has both a geometry and attributes.

To modify the example from Wikipedia, this is what a GeoJSON Feature would look like in your case:

{ "type": "Feature",
    "geometry": {
      "type": "Point", 
      "coordinates": [102.0, 0.5]
      },
    "properties": {
      "ipAddress": "X.X.X.X",
      "score": "1000"
      }
    }

And this would be an example FeatureCollection, in which you have multiple geometries with the attributes you specified.

{ "type": "FeatureCollection",
  "features": [
    { 
      "type": "Feature",
      "geometry": {
        "type": "Point", 
        "coordinates": [102.0, 0.5]
        },
      "properties": {
        "ipAddress": "X.X.X.X",
        "score": "1000"
        }
    }, {
    ...
    }
  ]
}

You may have noticed that JSON/GeoJSON syntax is similar to Python dictionaries and lists. In Python, you can directly dump a Python dictionary, with or without nested lists and dictionaries, into a JSON/GeoJSON file using the json module. Example:

import json

feature = {
    'type': 'Feature',
    'geometry': {
        'type': 'Point',
        'coordinates': [102.0, 0.5],
    },
    'properties': {
        'ipAddress': 'X.X.X.X',
        'score': '1000'
    }
}

# Convert to a JSON string
json.dumps(feature)

# Output to a file (JSON serialization)
with open('./some_file.json', 'w') as stream:
    json.dump(feature, stream, indent=2)

Here is the documentation on the json module for Python 2.

Related Question