我是TypeScript的新手,我一直坚持使用JSON。我需要创建一个简单的JSON对象,但我仍然没有这样做。这是我的第一次尝试:
output: JSON; //declaration
this.output = {
"col1":{"Attribute1": "value1", "Attribute2": "value2", "Attribute3": "value3"},
"col2":{"Attribute1": "value4", "Attribute2": "value5", "Attribute3": "value6"},
"col3":{"Attribute1": "value7", "Attribute2": "value8", "Attribute3": "value9"}
}
这不起作用。我想我应该使用JSON.stringify函数。这是我的尝试:
obj: any; //new object declaration
this.obj = {
"col1":{"Attribute1": "value1", "Attribute2": "value2", "Attribute3": "value3"},
"col2":{"Attribute1": "value4", "Attribute2": "value5", "Attribute3": "value6"},
"col3":{"Attribute1": "value7", "Attribute2": "value8", "Attribute3": "value9"}
}
this.output.stringify(this.obj);
但是这仍然会调用TypeError。总结一下我的问题:如何在TypeScript中正确创建和初始化JSON对象?
答案 0 :(得分:6)
我最终想通了。我所要做的就是将数据创建为“any”变量,如下所示:
output: JSON;
obj: any =
{
"col1":{"Attribute1": "value1", "Attribute2": "value2", "Attribute3": "value3"},
"col2":{"Attribute1": "value4", "Attribute2": "value5", "Attribute3": "value6"},
"col3":{"Attribute1": "value7", "Attribute2": "value8", "Attribute3": "value9"}
};
然后将其强制转换为JSON对象:
this.output = <JSON>this.obj;
答案 1 :(得分:3)
通过这样做,它在Angular 2.4.0 Stable中起作用了:
var request: any = {};
request.allocation = allocationFigure;
答案 2 :(得分:1)
您还可以执行以下操作
const rememberUser:JSON = <JSON><unknown>{
"username": this.credentialsForm.value.username,
"password": this.credentialsForm.value.password
}