【问题标题】:Initializing JSON object in TypeScript在 TypeScript 中初始化 JSON 对象
【发布时间】:2013-09-02 21:48:13
【问题描述】:

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

【问题讨论】:

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

标签: json typescript


【解决方案1】:

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

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;

【讨论】:

  • JSON 不是 JSON 对象的类型,而是 JSON 解析对象本身的类型。
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

    您还可以执行以下操作

    const rememberUser:JSON = <JSON><unknown>{
            "username": this.credentialsForm.value.username,
            "password": this.credentialsForm.value.password
          }
    

    【讨论】:

      猜你喜欢
      • 2014-05-18
      • 2019-03-08
      • 2017-12-26
      • 1970-01-01
      • 2018-02-10
      • 2013-06-27
      • 1970-01-01
      • 2016-09-01
      相关资源
      最近更新 更多