在TypeScript中初始化JSON对象 [英] Initializing JSON object in TypeScript

查看:1161
本文介绍了在TypeScript中初始化JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是TypeScript的新手,但我一直坚持使用JSON.我需要创建一个简单的JSON对象,但这样做一直失败.这是我的第一次尝试:

I'm new to TypeScript and I'm stuck at working with JSON. I need to create a simple JSON object and I keep on failing doing so. Here are my first attempts:

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函数.这是我的尝试:

This doesn't work. I guess I should work with JSON.stringify function. Here's my attempt:

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

But this still invokes TypeError. So to summarize my question: how to properly create and initialize JSON object in TypeScript?

推荐答案

我终于知道了.我要做的就是为任何"变量创建数据,如下所示:

I've eventually figured it out. All I had to do was to create data to "any" variable like this:

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对象:

and then cast it to JSON object:

this.output = <JSON>this.obj;

这篇关于在TypeScript中初始化JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆