-1

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?

Morteza Malvandi
  • 1,656
  • 7
  • 30
  • 73

4 Answers4

1

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);
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
1

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.

Nihar Sarkar
  • 1,187
  • 1
  • 13
  • 26
1

Valid JSON would be:

var text = '{"type": "name", "properties": {"name":"urn:ogc:def:crs:EPSG::3857"}}';

var obj = JSON.parse(text);
Setily
  • 814
  • 1
  • 9
  • 21
  • But his question is how to parse the string he has, not some other string. –  Aug 15 '16 at 06:46
0

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'}}"))();
Isaac
  • 11,409
  • 5
  • 33
  • 45
  • What is the advantage of this over `eval`? –  Aug 15 '16 at 12:36
  • 1
    @torazaburo you can cache functions, you can't cache eval. The scope is separated inside `new Function`, and `eval` is brought into the scope. http://stackoverflow.com/questions/4599857/are-eval-and-new-function-the-same-thing – Isaac Aug 15 '16 at 22:00