skip to Main Content

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

2

Answers


  1. Chosen as BEST ANSWER
    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.


  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search