Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conversion of string to JSON object in JavaScript with eval() [duplicate]

I am converting the following JSON variable to string. When back to JSON, I'm getting an error (in ReactJS, although it shouldn't be important).

var questionGlobal = {
  "questionCons": [{
    "string": "In",
    "alignment": 2
  }, {
    "string": "New York State",
    "alignment": 1
  }, {
    "string": "the",
    "alignment": -1
  }, {
    "string": "shortest",
    "alignment": -1
  }, {
    "string": "period",
    "alignment": 0
  }, {
    "string": "of",
    "alignment": 2
  }, {
    "string": "daylight",
    "alignment": 0
  }, {
    "string": "occurs",
    "alignment": 2
  }, {
    "string": "during",
    "alignment": 1
  }, {
    "string": "which",
    "alignment": 0
  }, {
    "string": "month",
    "alignment": 0
  }],
  "options": [{
    "string": "January",
    "alignment": 1
  }, {
    "string": "December",
    "alignment": 2
  }, {
    "string": "June",
    "alignment": 1
  }, {
    "string": "July",
    "alignment": 1
  }]
};

Here is the command:

window.console.log( eval(JSON.stringify(questionGlobal)));

The output that I get in console is:

Uncaught SyntaxError: Unexpected token

Any idea where I am doing it wrong?

like image 294
Daniel Avatar asked Dec 05 '22 21:12

Daniel


1 Answers

You could use JSON.parse.

console.log(JSON.parse(JSON.stringify(questionGlobal)));

When using eval() it is required that you pass a valid JS statement. One you could actually write without the eval and without getting any errors.

JSFiddle Demo

like image 61
Rey Libutan Avatar answered Dec 21 '22 23:12

Rey Libutan