【发布时间】: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