I have this string
var str = '{"{\n \"lightid\": \"ID1\",\n \"brightness\": \"123\",\n \"RGB\": \"1,2,3\"\n}":""}';
How do I parse it into JSON object?
I have this string
var str = '{"{\n \"lightid\": \"ID1\",\n \"brightness\": \"123\",\n \"RGB\": \"1,2,3\"\n}":""}';
How do I parse it into JSON object?
Just call:
JSON.parse('{\n \"lightid\": \"ID1\",\n \"brightness\": \"123\",\n \"RGB\": \"1,2,3\"\n}');
Your json
string is malformed. Currently, it is:
var str = '{"{\n \"lightid\": \"ID1\",\n \"brightness\": \"123\",\n \"RGB\": \"1,2,3\"\n}":""}';
which evaluates to
{"{
"lightid": "ID1",
"brightness": "123",
"RGB": "1,2,3"
}":""}
You need to use:
var str = '{\n \"lightid\": \"ID1\",\n \"brightness\": \"123\",\n \"RGB\": \"1,2,3\"\n}'
And use the default JSON parser:
var jsObj = JSON.parse(str);
console.log("jsonObj.brightness", jsonObj.brightness);
It seems you will have a list of such values. In this case, the probable construct will be:
var str = '[ {\n \"lightid\": \"ID1\",\n \"brightness\": \"123\",\n \"RGB\": \"1,2,3\"\n}, \n {\n \"lightid\": \"ID2\",\n \"brightness\": \"246\",\n \"RGB\": \"2,4,6\"\n} ]'
var jsArr = JSON.parse(str);
console.log("jsonObj[0].brightness", jsonObj[0].brightness);