Angular2 将字符串转换为 JSON
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40789120/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angular2 cast string to JSON
提问by F3L1X79
What is the right syntax to cast a string to JSON in Angular2? I tried:
在 Angular2 中将字符串转换为 JSON 的正确语法是什么?我试过:
var someString;
someString.toJSON(); //or someString.toJson();
it says: someString.toJSON is not a function
它说: someString.toJSON is not a function
I'm lost because it was working with Angular1.
我迷路了,因为它正在与 Angular1 一起工作。
If I try to add an attribute directly on my string (which is formatted like a true JSON):
如果我尝试直接在我的字符串上添加一个属性(其格式类似于真正的 JSON):
var someString;
someString.att = 'test';
it says: TypeError: Cannot create property 'att' on string '...'
它说: TypeError: Cannot create property 'att' on string '...'
回答by danday74
Angular2 uses JavaScript functions unlike Angular1.
与 Angular1 不同,Angular2 使用 JavaScript 函数。
Angular1 implements its own functions which is a bad thing.
Angular1 实现了自己的功能,这是一件坏事。
In Angular2 just use pure JavaScript.
在 Angular2 中只使用纯 JavaScript。
var json = JSON.parse(string);
回答by hzitoun
Try using JSON.parse()
尝试使用 JSON.parse()
var someString: string = "your JSON String here";
var jsonObject : any = JSON.parse(someString)

