how to convert { startItem: 2 } string to an object { "startItem": 2 } without using eval() function ?
{ startItem: 2 }
{ "startItem": 2 }
2
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.
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.
Click here to cancel reply.
2
Answers
This will work.
Use JSON.stringify()
Example run in chrome console:
And JSON.parse the other way :
Edit:
So you have a string ‘{ startItem: 2 }’. And you dont want to use eval, then you can use Function:
And then you can JSON.stringify this one.