Ardahan Kisbet Ardahan Kisbet - 6 months ago 37
jQuery Question

JSON.parse doesn't work in Javascript?

I am using ajax before page load for getting some Json string. From my handler I return string that formatted json. And I must use as json in javascript. To do that I try JSON.parse(myJsonString) and it don't work. When I alert that it doesn't show up. Where am I going wrong?

var geojsonObject2 ;
$.ajax({
url: "LoadHandler.ashx",
success: function getFromDBCallback(geojsonObject) {
//var temp='['+geojsonObject+']'// I also try that, it don't work
var obj = JSON.parse(geojsonObject);
alert(obj);// for checking but nothing show up here?
geojsonObject2 = obj;
},
async: false
});


and this is my Handler:

public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
#region json string
string geojsonObject = @"
{
'type': 'FeatureCollection',
'crs': {
'type': 'name',
'properties': {
'name': 'EPSG:4326'
}
},
'features': [
{
'type': 'Feature',
'properties': {
'any-property': 'feature1'
},
'geometry': {
'type': 'Point',
'coordinates': [21.54967, 38.70250]
}
},
{
'type': 'Feature',
'properties': {
'any-property': 'feature2'
},
'geometry': {
'type': 'LineString',
'coordinates': [
[21.54967, 38.70250], [22.54967, 39.70250]
]
}
}
]
}
";
#endregion
//context.Response.Write(js.Serialize(geojsonObject));
context.Response.Write(geojsonObject);
}

Answer

Try replacing single-quotes with doubles quotes as below, JSON.parse works if attribute names and values if they are enclosed in double-quotes:

string geojsonObject = @"
        {
        ""type"": ""FeatureCollection"",
        ""crs"": {
            ""type"": ""name"",
            ""properties"": {
                ""name"": ""EPSG:4326""
            }
        }...."
Comments