21

我是 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 对象?

4

3 回答 3

18

我终于想通了。我所要做的就是为“任何”变量创建数据,如下所示:

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;
于 2013-08-30T11:02:44.557 回答
10

您还可以执行以下操作

const rememberUser:JSON = <JSON><unknown>{
        "username": this.credentialsForm.value.username,
        "password": this.credentialsForm.value.password
      }
于 2019-04-25T07:10:07.813 回答
9

通过这样做,它在 Angular 2.4.0 Stable 中为我工作:

var request: any = {};
request.allocation = allocationFigure;
于 2017-03-04T05:03:32.820 回答