Home > Software design >  Converting object type string to an object?
Converting object type string to an object?

Time:11-24

how to convert { startItem: 2 } string to an object { "startItem": 2 } without using eval() function ?

CodePudding user response:

var aux = { startItem: 2 }
var jsonStr = aux.replace(/(\w :)|(\w  :)/g, function(matchedStr) {
                      return '"'   matchedStr.substring(0, matchedStr.length - 1)   '":';
});
var obj = JSON.parse(jsonStr);
console.log(obj);

This will work.

CodePudding user response:

Use JSON.stringify()

Example run in chrome console:

> JSON.stringify({ startItem: 2 })
  '{"startItem":2}'

And JSON.parse the other way :

> JSON.parse('{"startItem":2}')
  {startItem: 2}

Edit:

So you have a string '{ startItem: 2 }'. And you dont want to use eval, then you can use Function:

> const transform = (value) => Function(`return ${value}`)()
> transform('{ startItem: 2}')
  {startItem: 2}

And then you can JSON.stringify this one.

  • Related