Solace Solace - 1 year ago 72
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
. Please notice that the starting and ending
around the value of
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
to a JS object,
so that when I later convert
to JSON using
, the value of
becomes a JSON object, and the value of
becomes a JSON object nested inside the aforementioned JSON object.

Answer Source

Using JSON.parse():

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download