-1

I receive from WebSocket material like this:

{"sensorValue":{"id":5168,"roadStationId":23401,"name":"OHITUKSET_5MIN_LIUKUVA_SUUNTA2_MS2","oldName":"ohitukset_5min_liukuva_suunta2_MS2","shortName":"MTila2","sensorValue":69,"sensorUnit":"***"}}
{"sensorValue":{"id":5125,"roadStationId":23401,"name":"KESKINOPEUS_5MIN_LIUKUVA_SUUNTA2","oldName":"averageSpeed2","shortName":"km/h2","sensorValue":83,"sensorUnit":"km/h"}}

What I want to do is to get the values of name and sensorValue. So far I have code like this:

function connect() {
     var url = "ws://...";
     var socket = new WebSocket(url);
     socket.onopen = function (event) {
         console.info('Socket is open');
     }
     socket.onmessage = function(message) {
         addMessage(message);
     };
}


function addMessage(message) {
     var myJSON = JSON.stringify(message.data);
     var obj = JSON.parse(myJSON);
     document.getElementById("sensorValue").innerHTML = obj.sensorValue;
}

Now, whatever I do I get this:

uncaught TypeError: Cannot set property 'innerHTML' of null".

I have tried several web tutorials of getElementryById and they work just fine.

Why am I getting this error?

Jeff Mercado
  • 113,921
  • 25
  • 227
  • 248
JussiJ
  • 21
  • 2
  • 1
    Do you have an element in your HTML with the id sensorValue? – danielspaniol Jun 09 '17 at 15:48
  • 1
    First of: Calling `JSON.parse` directly after `JSON.stringify` is unnecessary. Just don't call `JSON.stringify` in the first place. Secondly that error means that the element with ID `sensorValue` doesn't exist. Make sure it does exist (either by creating it or by correcting the argument you pass). The error has nothing to do with *parsing* the data (which you don't have to do anyway if you don't serialize). – Felix Kling Jun 09 '17 at 15:48

1 Answers1

1

I think you are mixing 2 things together:

  1. you have your response data in JSON format and you want to read a specific value from it. You do this by referencing the needed field with dot operator. For ex: object.fieldName;(in your case obj.sensorValue)

  2. you want to display a specific value in your HTML page using: document.getElementById("sensorValue").innerHTML=value_to_display. For this to work you need to have a HTML element with id "sensorValue". The error you get tells you, there is no such element. For example, you could add a <div id="sensorValue"></div> to your page.

Juan Serrats
  • 1,330
  • 5
  • 21
  • 27
mihais
  • 35
  • 6
  • 1
    Nit: You cannot access data in "JSON format" with dot notation. JSON is *text*. It has to be parsed first to turn it into a JavaScript object, at which point it isn't JSON anymore. It seems like the OP just has an object. There is no need for `JSON.stringify` or `JSON.parse`. – Felix Kling Jun 09 '17 at 15:58