Search code examples
javascriptjsonapiopenlayersgeojson

How to delete an extra " in GEOjson (Javascript)


I tried to manipulate an object GEOjson to display it in my map OpenLayers. But my GEOjson is invalid. First, in my API I request to my database to recover the geometry, then I parse it thanks to GEOjson.parse : GeoJSON.parse(data, {GeoJSON : 'geometry'}); the data looks like this :

{
    "type": "FeatureCollection",
        "features": [
            {
                "type": "Feature",
                "geometry": "{\"type\":\"MultiPolygon\",\"coordinates\":[[[[0.699526704561417,49.5855766259652],[0.699132813373672,49.5855472259388],[0.698829663954256,49.5852457878428],[0.698308423811369,49.5855523688003],[0.699127661396565,49.5862481964213],[0.699752271011022,49.5859030239836],[0.699526704561417,49.5855766259652]]]]}",
                "properties": {
                    "libgeo": "Bois-Himont",
                    "nature": "Parcelle bâtie"
                }
            },
            {
                "type": "Feature",
                "geometry": "{\"type\":\"MultiPolygon\",\"coordinates\":[[[[0.696220319484454,49.581274516207],[0.696272071456392,49.5820438187077],[0.697147417334422,49.5815673912038],[0.697102005023975,49.5814546891317],[0.697047441685103,49.5812624281067],[0.6969844037675,49.5812621313821],[0.696220319484454,49.581274516207]]]]}",
                "properties": {
                    "libgeo": "Bois-Himont",
                    "nature": "Parcelle bâtie"
                }
            }, etc...

Then in my script.js (that files had the aim to display the map and the GEOjson) I parse the data thanks to JSON.parse, but the line geometry is invalid because there is an extra " and the type and the coordinates is surrounded by ".

How can I delete the extra " and delete the " for the type and the coordinates ?


Solution

  • The geometry is a string when it should be an object. After the first parse you will need loop through the features and parse each geometry string into an object.

    var myGeoJSON = JSON.parse(myText);
    myGeoJSON.features.forEach( function(feature) { feature.geometry = JSON.parse(feature.geometry) });