Niko Zarzani
Niko Zarzani

Reputation: 1402

Atmosphere using x-websocket

I am trying to get some data from an external (hence I don't know how it was configured) websocket API that uses Atmosphere (https://github.com/Atmosphere/atmosphere-javascript). I am using the x-websocket polymer element to manage my requests (https://github.com/elierotenberg/x-websocket).

This is the data I get in response to my request:

593|{{date.day.name EQUALS Friday; date.day EQUALS 8; date.month.name EQUALS August; date.month EQUALS 8; date.year EQUALS 2014; date.dow EQUALS 6; time.hour EQUALS 15; time.minute EQUALS 18; time.second EQUALS 48; time EQUALS 151848; date EQUALS 20140808; sender EQUALS Light; object.type EQUALS EnvObject.ElectricDevice.Light; object.name EQUALS Kitchen Light; object.protocol EQUALS unknown; object.address EQUALS unknown; object.uuid EQUALS 21969e70-7e00-4a0d-a13f-a4728240d9d0; object.currentRepresentation EQUALS 0; object.behavior.brightness EQUALS 0; object.behavior.powered EQUALS false}}

Does anybody have an idea of how to deserialize it in js or how to parse it into a JSON object?

Otherwise, do you have any hint of what is wrong with Atmosphere? (I can ask the API owner to configure it differently)

Upvotes: 0

Views: 159

Answers (1)

Niko Zarzani
Niko Zarzani

Reputation: 1402

I still don't know the response type but eventually I parsed the content, here's the code:

<script>
 Polymer({
  onMessage: function(event){
    var data = event.detail.data;
    data = data.split("|").pop();
    data = this.parse(data);
    this.fire("message", { data: data });
  },
  parse: function(input){
    var statements = input.substring(2, input.length -2).split("; ");
    var output = {};

    for (var i = 0; i < statements.length; i++) {
      var statement = statements[i].split(" EQUALS ");
      var leftSide = statement[0].split(".");
      var rightSide = statement[1];
      this._assign(output, leftSide, rightSide);
    }

    var data = JSON.stringify(output);
    return JSON.parse(data);
  },
  _assign: function(obj, keyPath, value){
     var lastKeyIndex = keyPath.length-1;
     for (var i = 0; i < lastKeyIndex; ++i) {
       key = keyPath[i];
       if (!(key in obj)){
         obj[key] = {};
       }
       obj = obj[key];
     }
     obj[keyPath[lastKeyIndex]] = value;
  }
});

Upvotes: 1

Related Questions