morteza malvandi morteza malvandi - 8 months ago 30
JSON Question

How to parse special string as JSON?

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'}}" + ')');


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, '"'));


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"}}');