F3L1X79
F3L1X79

Reputation: 2665

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 '...'

Upvotes: 15

Views: 78250

Answers (2)

hzitoun
hzitoun

Reputation: 5832

Try using JSON.parse()

var someString: string = "your JSON String here";
var jsonObject : any = JSON.parse(someString)

Upvotes: 4

danday74
danday74

Reputation: 56946

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);

Upvotes: 44

Related Questions