1

I am receiving Data from an MQTT Server, which is giving me data after some intervals. The Data received is in the form of JSON Object. I want to store the values of the data that I get and then pass it to my Database. But I am getting error Accessing its Keys.

This is my Function which is fetching the JSON Data.

function mqtt_messsageReceived(topic, message, packet) {


    if(message !== null && message !== undefined )
    {
        var myMessages = message;
       console.log('Messages are '+ myMessages);


    }

};

This is my Console Log JSON Data.

Messages are {"Temp":26.50,"Door":1,"Fan1":0,"Fan2":0,"Time":"22-8-2018 16:05","mac":"5ccf7f5a4ba4"}

I Want to access Temp from this JSON Object.

I have tried doing :

console.log('Temp is '+myMessages.Temp);

But it only gives me an Error - Temp is undefined. I have Tried Fetching many ways, one way was with Object.values

var myMessages = Object.values(message); 

All I get is some random numbers

My  Messages are 123,34,84,101,109,112,34,58,50,52,46,53,48,44,34,68,111,111,114,34,58,49,44,34,70,97,110,49,34,58,48,44,34,70,97,110,50,34,58,49,44,34,84,105,109,101,34,58,34,50,50,45,56,45,50,48,49,56,32,49,54,58,49,54,34,44,34,109,97,99,34,58,34,53,99,99,102,55,102,53,97,52,98,97,52,34,125,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0

Can anyone Help here ??

codemt
  • 413
  • 2
  • 9
  • 25
  • 1
    look at [`JSON.parse`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse) – jonatjano Aug 22 '18 at 10:51
  • 2
    [There's no such thing as a "JSON Object"](http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/) – Andreas Aug 22 '18 at 10:53
  • @jonatjano i found the solution to this. the JSON which was being received had some hidden special characters had to clean those characters. and no JSON.parse is working properly. and i am able to get obj.Temp and other values. – codemt Aug 22 '18 at 12:02
  • I indicated it because there was no visible call to It in your question so I wasn't even sure you called it somewhere before, don't forget to include it next time, seems like @JasminMistry made the same assumption – jonatjano Aug 22 '18 at 12:09

1 Answers1

-2

You can use JSON.parse:

console.log(JSON.parse(myMessages)["Temp"]);
Luca Kiebel
  • 9,790
  • 7
  • 29
  • 44
Jasmin Mistry
  • 1,459
  • 1
  • 18
  • 23
  • `myMessages.Temp` and `myMessages["Temp"]` are equivalent. If one is `undefined` then so is the other. – Quentin Aug 22 '18 at 10:52
  • In general, you should explain why the change you recommend will fix the problem and not just post code with which people can play spot-the-difference. Unfortunately, the difference here doesn't fix the problem. – Quentin Aug 22 '18 at 10:52
  • its still logging "undefined". both ways i have tried. even storing it in a seperate variable i have tried. – codemt Aug 22 '18 at 10:55