在Angular 2中,如果想要打印JSON嵌套数组,可以使用JSON.stringify()
方法将其转换为字符串,然后打印。下面是一个示例代码:
export class AppComponent implements OnInit {
jsonData: any = {
name: "John",
age: 30,
hobbies: ["reading", "playing", "coding"],
address: {
street: "123 Main St",
city: "New York",
state: "NY"
}
};
ngOnInit() {
console.log(JSON.stringify(this.jsonData));
}
}
在上面的代码中,jsonData
是一个包含嵌套数组的JSON对象。通过调用JSON.stringify()
方法,将jsonData
转换为字符串,并通过console.log()
方法打印出来。
当在浏览器的控制台中运行这段代码时,将会打印出以下结果:
{"name":"John","age":30,"hobbies":["reading","playing","coding"],"address":{"street":"123 Main St","city":"New York","state":"NY"}}
注意:JSON.stringify()
方法还可以接受其他参数,用于格式化输出的字符串,例如JSON.stringify(this.jsonData, null, 2)
可以在打印时使用2个空格进行缩进。