Divyesh Kumar
Divyesh Kumar

Reputation: 37

How to get Particular Value from JsonObject?

This is my Json Object and I am trying to retrieve the data from it but I am getting as undefined ,

{
    "status": 200,
    "message": "Task has been Retrieved",
    "employeepanel": {
        "taskno": 7,
        "taskdate": "2001-06-21",
        "createdby": "admin",
        "taskdescription": "create the product and deliever it by monday  ",
        "status": "assigned",
        "date": "2001-06-21",
        "tenure": 1,
        "employee": {
            "userId": 30,
            "userName": "xyz",
          
        }
    }
}

This is what I was trying to do , my function finds the task by id , and my api gives response in such format now I have to get the userName from this

findbyId(event) {
    var selected_id = event.currentTarget.id
    const base_URL = 'http://localhost:8091/getbyTaskno/'+selected_id 
    this.http.get(base_URL, {
    }).subscribe(data => {
      if (data['status'] == '200' && data['message'] == 'Task has been Retrieved') {
      this.userIds=data['employeepanel.employee.userName']
     }else{
       alert("No task is present for the particular Employee")
     } })
  }

Upvotes: 0

Views: 112

Answers (2)

Lakshaya U.
Lakshaya U.

Reputation: 1181

data['employeepanel.employee.userName'] is wrong notation.

This would be sample code, assuming data is valid JSON:

findbyId(event) {
    var selected_id = event.currentTarget.id;
    const base_URL = 'http://localhost:8091/getbyTaskno/'+selected_id;
    this.http.get(base_URL, {
    }).subscribe(data => {
        if (data.status === '200' && data.message === 'Task has been Retrieved') {
            this.userIds=data.employeepanel.employee.userName;
        } else {
            alert("No task is present for the particular Employee")
        }
    });
}

For better reference to JSON have a look at this.

let data = {
    "status": 200,
    "message": "Task has been Retrieved",
    "employeepanel": {
        "taskno": 7,
        "taskdate": "2001-06-21",
        "createdby": "admin",
        "taskdescription": "create the product and deliever it by monday  ",
        "status": "assigned",
        "date": "2001-06-21",
        "tenure": 1,
        "employee": {
            "userId": 30,
            "userName": "xyz",
        }
    }
};

function getEmployeeUserName() {
  console.log("data.employeepanel.employee.userName is: ", data.employeepanel.employee.userName);
}
.main {
  font-size: 20px;
}
<p class="main">Click the button to log the <code>.employeepanel.employee.userName;</code></p>
<button onclick="getEmployeeUserName()">Get Employee userName</button>

Upvotes: 2

KreepN
KreepN

Reputation: 8598

Try accessing your properties and sub props with dot notation:

this.userIds=data.employeepanel.employee.userName;

Upvotes: 2

Related Questions