F3L1X79 F3L1X79 - 11 days ago 6
JSON Question

Angular2 cast string to JSON

What is the right syntax to cast a string to JSON in Angular2?
I tried:

var someString;
someString.toJSON(); //or someString.toJson();


it says:
someString.toJSON is not a function


I'm lost because it was working with Angular1.




If I try to add an attribute directly on my string (which is formatted like a true JSON):

var someString;
someString.att = 'test';


it says:
TypeError: Cannot create property 'att' on string '...'

Answer

Angular2 uses JavaScript functions unlike Angular1.

Angular1 implements its own functions which is a bad thing.

In Angular2 just use pure JavaScript.

var json = JSON.parse(string);
Comments