chink
chink

Reputation: 1643

Accessing elements in a json object

I have several questions how to access the json object, but my question is slightly different. my json object looks bit different

this is my json object

data = ["data","{\"id\":\"fd00::212:4b00:197b:274a\",\"counter\":30,\"temperature\":2622,\"humidity\":4617,\"battery\":2828,\"timestamp\":\"04:48:50.816305\",\"date\":\"2019-04-26\",\"deviceType\":\"milo\"}"]

I want to access elements with in this json object

  realTime() {
    this.webSocket.connect()
      .subscribe(
        (data:any) => {
          console.log(data)
          console.log(data[1].temperature)
          this.device_id = data.id
          this.temperature = data.temperature
          this.humidity = data.humidity
        })

  }

I have tried but not able to access the elements properly

Upvotes: 1

Views: 1508

Answers (2)

AyushKatiyar
AyushKatiyar

Reputation: 1030

JSON works on key value pair so try using the below solution to do so.

realTime() {
    this.webSocket.connect()
      .subscribe(
        (data:any) => {
          console.log(data);
          console.log(data[1]["temperature"]);
          this.device_id = data[1]["id"];
          this.temperature = data[1]["temperature"];
          this.humidity = data[1]["humidity"];
        })

  }

Upvotes: 0

Pranav C Balan
Pranav C Balan

Reputation: 115212

The data[1] holds a JSON string, not an object so you have to parse it using JSON.parse method.

console.log(JSON.parse(data[1]).temperature);

Final code:

realTime() {
    this.webSocket.connect()
      .subscribe((data:any[]) => {
         console.log(data)
         let data1 = JSON.parse(data[1]);
         console.log(data1.temperature)
         this.device_id = data1.id
         this.temperature = data1.temperature
         this.humidity = data1.humidity
      })

}

Upvotes: 1

Related Questions