在TypeScript中初始化JSON对象

Out*_*ger 13 json typescript

我是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)

  • JSON不是JSON对象的类型,而是JSON解析对象* self *的类型。 (6认同)
  • @RyanCavanaugh 这是一个非常有价值的见解,隐藏在评论中!我本来想问你逻辑上的后续问题,即:JSON 数据的_正确_类型是什么,但在简单检查“JSON.parse()”的返回类型后,答案似乎是“any” (2认同)

kat*_*n A 7

您还可以执行以下操作

const rememberUser:JSON = <JSON><unknown>{
        "username": this.credentialsForm.value.username,
        "password": this.credentialsForm.value.password
      }
Run Code Online (Sandbox Code Playgroud)


Abd*_*ala 5

通过这样做,它在Angular 2.4.0中对我有用:

var request: any = {};
request.allocation = allocationFigure;
Run Code Online (Sandbox Code Playgroud)