Solace Solace - 5 months ago 8
JSON Question

How to convert a String that looks like JSON or a JS object, to an actual JS object?

The String I am talking about was initially a part of a JS object like:

var nameVal = "Jacob";
var favNumbersVal = "{\"firstNum\":0, \"secondNum\":1, \"thirdNum\":2}";

var aJSObject = {
"name" = nameVal,
"favNumbers" = favNumbersVal
};


The variable I am interested in is
favNumbersVal
. Please notice that the starting and ending
"
around the value of
favNumbersVal
are the normal double quotes we put around a String whenever we define a String.

The format of the value of favNumbersVal is coming from a library dynamically.

The question is that how do I convert the value of
favNumbersVal
to a JS object,
so that when I later convert
sJSObject
to JSON using
JSON.stringify()
, the value of
aJSObject
becomes a JSON object, and the value of
favNumbers
becomes a JSON object nested inside the aforementioned JSON object.

Answer

Using JSON.parse():

var favNumbersVal =  "{\"firstNum\":0, \"secondNum\":1, \"thirdNum\":2}";
console.log(JSON.parse(favNumbersVal));

Comments