直接访问 JSON 对象属性并记录它

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38148101/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 18:29:21  来源:igfitidea点击:

Accessing JSON object properties directly and log it

jsontypescriptangular

提问by Anna

I'm trying to access JSON Object properties directly and log it, here is my function :

我正在尝试直接访问 JSON 对象属性并记录它,这是我的函数:

loadProcesses(filter?){

this._postService.getAllProcess(filter)
.subscribe(
    res=> {
        this.processListe = res;
       // console.log(this.processListe.)
    }
,null,
() =>{
    console.log("get processes liste" + filter)

});

So this.processListe contain a JSON Object, and my JSON format is like this:

所以 this.processListe 包含一个 JSON Object,我的 JSON 格式是这样的:

{"Person": {
   "id": "A256",
   "name": "GET",
   "status": "active",
   "description": "hardworking, openminded",
   ...

So it will contains exactly the same things, for example if i want to simply print the label on a console log how can i do it ??

所以它将包含完全相同的东西,例如,如果我想简单地在控制台日志上打印标签,我该怎么做?

采纳答案by Alok Jha

Are you looking for something like this:

你在寻找这样的东西:

function parseObject(obj)
{
   for(var key in obj)
   {
      console.log("key: " + key + ", value: " + obj[key])
      if(obj[key] instanceof Object)
      {
        parseObject(obj[key]);
      }
   }
}

just call parseObject(res) in the subscribe method.

只需在 subscribe 方法中调用 parseObject(res) 即可。

回答by giannisf

parse it and access the fields.

解析它并访问字段。

var obj = JSON.parse(filter);
obj.Person.id; 
//etc

回答by Jarod Moser

parse it in the .subscribe:

在 .subscribe 中解析它:

res => this.processListe = res.json();

回答by Brahim LAMJAGUAR

a better solution is to declare your response with any :

更好的解决方案是使用 any 声明您的响应:

loadProcesses(filter?){

this._postService.getAllProcess(filter)
.subscribe(
    (res: any)=> {
        this.processListe = res;
       // console.log(this.processListe.)
    }
,null,
() =>{
    console.log("get processes liste" + filter)

});

this way you can access any attirbute in your response

这样你就可以在你的回复中访问任何属性