1

I have below line in my Controller class:

this.template.convertAndSend("/topic/greetings", message);

message is an arrayList. In a jsp file I open a socket and subscribe to "topic/greetings". I'm trying to access a field in the body of the message sent by Controller: so I'm doing this:

var stompClient = null;
var socket = new SockJS('/gs-guide-websocket');
stompClient = Stomp.over(socket);
stompClient.connect({}, function(frame) {
   stompClient.subscribe('/topic/greetings', function(message) {
     console.log(message.body);
   }
}

This prints below line on console of browser:

[  
  {  
    "_id":{  
      "timestamp":1487493075,
      "machineIdentifier":1371548,
      "processIdentifier":-28904,
      "counter":16629528,
      "date":1487493075000,
      "time":1487493075000,
      "timeSecond":1487493075
    },
    "name":"Alex",
    "age":25
  }
]

I want to access field name of that object. message.body.name prints undefined. I also tried:

var obj = JSON.parse(message.body);
console.log(obj.name);

or

console.log(obj["name"]);

but they are all undefined.

UPDATE:

I'd seen link, but my mistake was trying:

var obj = message.body;
console.log(obj[0]);

instead of this one:

var obj = JSON.parse(message.body);
console.log(obj[0].name);
Community
  • 1
  • 1
ShakibaZar
  • 727
  • 3
  • 9
  • 27

1 Answers1

1

please note that message.body is an array so use this:

console.log(obj[0]["name"]);
Bartek Fryzowicz
  • 6,464
  • 18
  • 27