Retrieve data from JSON fields within the message body

One question I have regarding the implementation in my Controller class involves the following line:

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

The 'message' being sent is an arrayList. In a JSP file, I establish a socket connection and subscribe to "topic/greetings". My goal is to access a specific field within the message body sent by the Controller. To achieve this, I have the following code:

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);
   }
}

Upon executing this code, the following data is displayed on the browser's console:

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

My objective is to access the 'name' field of the object. However, when attempting message.body.name, it returns undefined. I've also tried:

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

or

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

but unfortunately, they all result in undefined values.

UPDATE:

I came across a helpful link, but the mistake I made was trying:

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

instead of using:

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

Answer №1

It is important to remember that message.body should be treated as an array and accessed like this:

console.log(data[0]["title"]);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using DIV to "enclose" all the elements inside

I need assistance with my HTML code. Here is what I have: <div id="cover" on-tap="_overlayTapped" class$="{{status}}"> <form method="POST" action="/some/action"> <input required id="name" name="name" label="Your name"></input> ...

Module for Npm that includes unique code for both proxy support and non-proxy support configurations

Is there a way to develop a javascript library (available as a module on npm) with multiple implementations based on the level of proxy support in the environment where it is executed (transpiled to)? From my understanding, babel may not easily transpile ...

Transferring data between Javascript and PHP with AJAX and JQuery

I'm currently working on a basic web page that involves sending data from an HTML page to a PHP script and receiving some data back. My approach involves using AJAX, but for some reason, the PHP script doesn't seem to execute at all. Here's ...

jQuery fails to function properly when using the .live("keyup") event

Below is the code snippet: $(document).ready(function() { $("#querybox").live("keyup", function(e) { var code = (e.keyCode ? e.keyCode : e.which); if (code == 13) { $("#querybox").blur(); } else { search(document.getElementB ...

What is the reason for being able to update mysql with ajax, but not being able to access values from a mysql

Everything is contained within a single PHP file Here is the HTML code: <td> <input type="text" name="date_day1" id="date_day1" value="<?php echo $_POST['date_day1']?>" size="1"> </td> <t ...

Suggestions to reduce our website loading time

Query: How can one effectively reduce the file size of a webpage to improve loading speed? What specific optimization practices and coding techniques (in JavaScript and PHP) can be implemented to decrease page weight? Motivation: After reading an article ...

Oops, it seems like there was an issue with NextJS 13 Error. The createContext functionality can only be used in Client Components. To resolve this, simply add the "use client" directive at the

**Issue: The error states that createContext only works in Client Components and suggests adding the "use client" directive at the top of the file to resolve it. Can you explain why this error is occurring? // layout.tsx import Layout from "./componen ...

What is the best way to retrieve information from an API endpoint?

I have set up my frontend using nextjs (running on port 3000) and am attempting to fetch data from API endpoints in strapi (running on port 1337). How can I configure my frontend application to successfully retrieve data from the backend? Is there a way to ...

Working with JSON data and inserting it into MongoDB using PLAY-2.7 with Scala version 2.12

Can someone assist me with the process of converting a model (such as a user with a name field) into a JSON format and saving it to MongoDB? ...

What is the best way to incorporate HTML and JavaScript into an Angular view?

Within my markup, there is a substantial chunk of code enclosed with ng-controller tags. The structure resembles this: <div ng-controller="MyController"> <script> // MyController is initialized with current_item_data to streamline ...

Incorporating DefinitelyTyped files into an Angular 2 project: A step-by-step guide

I am currently developing an application using angular 2 and node.js. My current task involves installing typings for the project. In the past, when starting the server and activating the TypeScript compiler, I would encounter a log with various errors rel ...

What is the process of creating a mongoDB schema object in JavaScript when dealing with dynamically changing keys in a JSON?

I need to design a schema in mongoDB for an AngularJS project, but the json keys are dynamic. The structure of the json is as follows: { “1” : { “Name” : “John”, “City” : “London” }, “2” : { ...

Constructing items within an array literal using a constructor method

I am attempting to create an object using my Person constructor. However, I am encountering issues when I try to initialize the object directly in the array using literal notation. function Person(name, age) { this.name = name; this.age = age; } ...

Utilizing PHP to share content on Facebook

I am encountering an issue on a particular page of mine where there are multiple images. Each image has its own share and like button. When I click on the share button, I expect to share that specific image but it is not working as expected. Can someone pl ...

Extracting JSON data from a string using jQuery

http://localhost/project1/index.php //AJAX region $(function(){ $.ajax({ type : 'GET', url : 'https://jsonplaceholder.typicode.com/posts/1', success : function(data){ console.log('success \n', data); }, error ...

Issue with JQuery form submission without page refresh is not functioning as a result of a conflict with other JQuery

Within my code, I have implemented two different jQuery functionalities. One is used for handling form submissions and the other is utilized for creating modal popup windows. <script src="js/jquery-min.js" type="text/javascript"></script> is s ...

Transforming web content from HTML into text format and subsequently reinserting it into HTML for webpage integration

Our current process involves using an XML feed along with jquery and ajax to retrieve data, which is then parsed for display on the webpage. var des = $(this).find("Description").text(); var trimmed= des.substring(0, 300); if (trimmed.length <= 300) { ...

Creating arrays with ID numbers as keys leads to the generation of numerous other arrays, each with keys less than the specified number

I need to categorize an array based on a specific number (idGroup variable - integer) which is 3355 in this scenario. Below is the code I am using: if (sortedReservationsByGroup['grouped'] === undefined) { sortedReservationsByGroup[& ...

Using a uibCollapse within a nested directive element may not function as expected

Whenever I try to click on my custom directive, the elements that are supposed to expand remain collapsed. To ensure that the click event is actually triggered, I have specified a size in the css for the .btn class. // index.html <body ng-controller=" ...

How can I make an image the background on a webpage when clicking the mouse?

I find myself in a predicament without any code to guide me. The idea seems simple - I desire the ability to select an image from a collection and set it as the background image for the webpage. While I understand that JavaScript is essential for this tas ...