I have a string as follows:
"{'type': 'name', 'properties': {'name': 'urn:ogc:def:crs:EPSG::3857'}}"
I want to parse this string as JSON.
How can I do that?
I have a string as follows:
"{'type': 'name', 'properties': {'name': 'urn:ogc:def:crs:EPSG::3857'}}"
I want to parse this string as JSON.
How can I do that?
 
    
    The string you are provided is not valid JSON. There are two options either use eval() method or make it valid JSON and parse.
Using eval() method :
var obj = eval('(' + "{'type': 'name', 'properties': {'name': 'urn:ogc:def:crs:EPSG::3857'}}" + ')');
var obj = eval('(' + "{'type': 'name', 'properties': {'name': 'urn:ogc:def:crs:EPSG::3857'}}" + ')');
console.log(obj);But I don't prefer eval() method, refer : Don't use eval needlessly!
Or converting it to valid JSON by replacing single quotes with double quotes:
var obj = JSON.parse("{'type': 'name', 'properties': {'name': 'urn:ogc:def:crs:EPSG::3857'}}".replace(/'/g,'"'));
var obj = JSON.parse("{'type': 'name', 'properties': {'name': 'urn:ogc:def:crs:EPSG::3857'}}".replace(/'/g, '"'));
console.log(obj);FYI : The above code only works when there is no ' (single quote) within property name or value otherwise which replaced by ". For generating JSON in that case you need to use much complex regex.
But it always better to initialize string itself as a valid JSON and parse it using JSON.parse() method. 
{"type": "name", "properties": {"name": "urn:ogc:def:crs:EPSG::3857"}}
var obj = JSON.parse('{"type": "name", "properties": {"name": "urn:ogc:def:crs:EPSG::3857"}}');
console.log(obj); 
    
    Try this :
Replace all single quotes (') with double quotes (").
 var s={
        "type": "name",
        "properties": {
            "name": "urn:ogc:def:crs:EPSG::3857"
        }
    }
The JavaScript function JSON.parse(text) can be used to convert a JSON text into a JavaScript object:
 var j=JSON.parse(x);
Now the variable j has the JavaScript object.
 
    
    Valid JSON would be:
var text = '{"type": "name", "properties": {"name":"urn:ogc:def:crs:EPSG::3857"}}';
var obj = JSON.parse(text);
 
    
    If you want to avoid eval and want to avoid formatting the string for JSON.parse, you could try:
var jsonStr = "{'type': 'name', 'properties': {'name': 'urn:ogc:def:crs:EPSG::3857'}}";
var jsonFn = new Function("return "+jsonStr);
var json = jsonFn();
Or directly:
var json = (new Function("return {'type': 'name', 'properties': {'name': 'urn:ogc:def:crs:EPSG::3857'}}"))();
