-3

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?

Eddie
  • 26,593
  • 6
  • 36
  • 58
user3736228
  • 273
  • 3
  • 18

2 Answers2

0

Just call:

JSON.parse('{\n  \"lightid\": \"ID1\",\n  \"brightness\": \"123\",\n  \"RGB\": \"1,2,3\"\n}');
0

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);
vfalcao
  • 332
  • 1
  • 3
  • 12