Skip to content
Advertisement

JSON can’t read value of field [Vue.js]

JavaScript

I have function

JavaScript

Short explanation of function:

I call it in <child-component :value=valueOfMeasurement(measurement)></child-component> to pass it value to child component. measurement is JSON object that I use to identify which component and data is used,

measurement.fieldId have values 1,2,3…

message is JSON array which I get via REST and MQTT Api.I use REST to get current values (because MQTT has few minutes delay before reading any data, and then MQTT to get new values without refreshing page. I call REST first to get initial value in beforeMounted and then my message have value:

JavaScript

This is used in else part of function above, and it pass values normally.

After that, in my mounted() I call another functions that get message from MQTT protocol. It has delay of about 5 mins before it get any message from this protocol. Now this is where problems begin. If I put <div> {{this.message}} </div> I get normal message from MQTT as JSON object:

JavaScript

But if I console.log(this.message) inside function valueOfMeasurement(measurement) I get arrays of Uint8Array. That’s why I did this.currentMessage = enc.decode(this.message); and when I console.log(this.currentMessage) I get normal JSON object but, in same function, line under it, I try console.log(this.currentMessage["field1"] and I get undefined.

Also, in my <div>this.currentMessage</div> when I restart page I get test on my screen, which is ok, because I set it in data, but when code gets into this function valueOfMeasurement(measurement) and into if-loop I get error in console Reference error: currentMessage is not defined and in same console, next 5 lines are:

current message:

JavaScript

undefined undefined undefined.

These 5 console.logs are from valueOfMeasurement(measurement).

Advertisement

Answer

Problem is that enc.decode() returns string and not JSON, so I need to add JSON.parse

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement