我是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"}
}
Run Code Online (Sandbox Code Playgroud)
这不起作用.我想我应该使用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);
Run Code Online (Sandbox Code Playgroud)
但是这仍然会调用TypeError.总结一下我的问题:如何在TypeScript中正确创建和初始化JSON对象?
Out*_*ger 10
我终于想通了。我要做的就是为“任何”变量创建数据,如下所示:
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"}
};
Run Code Online (Sandbox Code Playgroud)
然后将其转换为JSON对象:
this.output = <JSON>this.obj;
Run Code Online (Sandbox Code Playgroud)
您还可以执行以下操作
const rememberUser:JSON = <JSON><unknown>{
"username": this.credentialsForm.value.username,
"password": this.credentialsForm.value.password
}
Run Code Online (Sandbox Code Playgroud)
通过这样做,它在Angular 2.4.0中对我有用:
var request: any = {};
request.allocation = allocationFigure;
Run Code Online (Sandbox Code Playgroud)