在TypeScript中初始化JSON对象

在TypeScript中初始化JSON对象,json,typescript,Json,Typescript,我是TypeScript的新手,我一直在使用JSON。我需要创建一个简单的JSON对象,但这样做一直失败。以下是我的第一次尝试: output: JSON; //declaration this.output = { "col1":{"Attribute1": "value1", "Attribute2": "value2", "Attribute3": "value3"}, "col2":{"Attribute1": "value4", "Attribute2": "value5", "Att

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

我最终找到了答案。我所要做的就是为“任何”变量创建数据,如下所示:

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;
this.output=this.obj;

在Angular 2.4.0稳定版中,通过这样做,它对我有效:

var request: any = {};
request.allocation = allocationFigure;

您还可以执行以下操作

const rememberUser:JSON = <JSON><unknown>{
        "username": this.credentialsForm.value.username,
        "password": this.credentialsForm.value.password
      }
const rememberUser:JSON={
“用户名”:this.credentialsForm.value.username,
“密码”:this.credentialsForm.value.password
}

你的例子对我来说没有多大意义。首先,你不能像那样在这个范围内声明输出,其次,如果你能提供你得到的确切错误,这将是很方便的。我发布了我为我的问题所做的解决方案,但它们不能很好地工作。我需要做的就是正确地创建一个JSON对象,并在我的TypeScript方法中初始化它。我发布的代码是可编译的-它没有显示任何错误,但在控制台中我可以看到TypeError“this.output is not defined”。正确的解决方案是在thisJSON的范围内声明输出不是JSON对象的类型,而是JSON解析对象本身的类型。