Converting a JavaScript object to JSON within Node-RED

I am attempting to convert a JavaScript object created in my Node-RED flow to JSON format, but I am struggling to figure out how to do it. The object consists of an hour and minute displayed on the screen, such as "13:02". I need to see this in JSON format on the "result" screen.

{"time": "hh: mm"}

However, I am only seeing "hh:mm" on the screen and I believe it is not in JSON format.

Additionally, when I submit the URL to a client's web service and try to view the JSON result, I receive the following error: There was an error parsing JSON data

Below is the code snippet I am using:

msg.headers = {"Content-type" : "application/json"}
var now = new Date(); 
var hour = now.getHours();
var minute = now.getMinutes();
if(hour.toString().length == 1) {
var hour = '0'+hour;}
if(minute.toString().length == 1) {
var minute = '0'+minute;
}
msg.payload = hour+':'+minute;
JSON.stringify({"time": msg.payload});
return msg;

The debug message indicates that it is a string:

https://i.sstatic.net/v3tae.jpg

Answer №1

When it comes to returning a JSON object, it is advised not to use the JSON.stringify() function. Instead, construct the object you wish to send in the payload field.

msg.headers = {"Content-type" : "application/json"}
var now = new Date(); 
var hour = now.getHours();
var minute = now.getMinutes();
if(hour.toString().length == 1) {
  hour = '0'+hour;
}
if(minute.toString().length == 1) {
  minute = '0'+minute;
}
msg.payload = {
  "time": hour+':'+minute
}
return msg;

If there is a need to convert objects to strings and vice versa, it is recommended to use the JSON node from the palette to handle the conversion of msg.payload.

https://i.sstatic.net/4HwgC.png

Answer №2

Store the outcome in a variable. Using JSON.stringify will give you a fresh object: msg won't be altered.

msg.payload = hour+':'+minute;
var newMsg = JSON.stringify({"time": msg.payload});
return newMsg;

Illustration

var msg = {};

var now     = new Date(); 
var hour    = now.getHours();
var minute  = now.getMinutes();

if(hour.toString().length == 1) {
  hour = '0'+hour;
}

if(minute.toString().length == 1) {
  minute = '0'+minute;
}
msg.payload = hour+':'+minute;
var newMsg = JSON.stringify({"time": msg.payload});
console.log(newMsg);

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

The react-bootstrap implementation is not functioning as expected, resulting in an unsupported server component error

Having an issue with an Unsupported Server Component Error while using react-bootstrap with typescript. I've shared the contents of my page.tsx file, layout.tsx file, and the specific error message. layout.tsx file import type { Metadata } from &apos ...

What is the @page rule in Material-UI?

Trying to incorporate Material-UI styles with react-to-print to print components can be tricky, especially when dealing with a specific component that requires a particular page size. Here's an attempt at achieving this: const styles = (theme: Theme) ...

Utilizing absolute positioning with a rotated div element

The situation I am facing involves a parent div and child div. The child div is positioned absolutely with respect to the parent div and has been rotated by an angle of 90 degrees. Due to the fact that the origin is located at the center of the child div ( ...

Struggling to link an external JavaScript file to your HTML document?

While attempting to run a firebase app locally, I encountered an error in the chrome console: GET http://localhost:5000/behaviors/signup.js net::ERR_ABORTED 404 (Not Found) Do I need to set firebase.json source and destination under rewrites or add a rout ...

Magento issue with unresponsive image map functionality

My website is built using the Ultimo theme in Magento, and I have implemented a script from to make the image map responsive. Here is the HTML code: <img name="sale" src="sale_1.jpg" width="1180" height="200" id="sale" usemap="#m_sale" alt="" />< ...

No matter what I try, the design of my dialog box remains stubbornly unchanged

I am attempting to increase the width of my dialog box while also adding horizontal middle borders. It seems that my bootstrap for the site does not include these elements. How can I rectify this issue? Here is my code: $(document).ready(function() { ...

Deliver the AJAX response of success to a modal in jQuery

Is there a way to send an ajax success response to a jQuery Modal (jQuery Modal Site) when clicking submit and have the modal automatically display the response? Here is my current ajax post code: $('#rincian').submit(function() { $.ajax({ ...

Using a PHP WordPress Loop, eliminate the comma following the final object in the Schema array

My Google Schema Markup for a "Product" includes a loop that displays "Reviews". Below is an excerpt of the code: "review": [ <?php $args = array( 'post_type' => 'my_reviews', & ...

Working with PHP results in JSON outputs containing arrays

I need help processing the JSON result: ["13:00:00","14:00:00"] in my mobile application using Java language. The JSON may vary in length, with a maximum of 8 items or 8 hours. I send a PHP request from my application, triggering a query to run and return ...

Generating a fresh object from an existing object by incorporating updated values using Angular and Ionic version 3

Currently, I am actively working on an Ionic 3 project that utilizes Angular framework. Within my project, I have a JSON object called 'person' which consists of data fields such as name, job, and home. One feature in my app is an Ionic toggle b ...

Converting a string into a list extracted from a text document

Within a file, the data (list) is structured as follows: [5,[5,[5,100,-200],200,-400],300,-500] Upon reading this file in an angular application, the contents are converted into a string object like so: "[5,[5,[5,100,-200],200,-400],300,-500]" Is there ...

A simple guide to running Express Js and MongoDB from the command line and gracefully closing the terminal

Is there a way to run an Express project without the terminal being visible or easily closed? I need my server to stay running, but I don't want the user on the local PC to be able to see or close the terminal. Any suggestions on how to achieve this ...

What is the best way to retain checkbox states after closing a modal?

I have a modal that includes multiple checkboxes, similar to a filter... When I check a checkbox, close the modal, and reopen it, the checkbox I clicked on should remain checked. (I am unsure how to achieve this :/) If I check a checkbox and then click t ...

Testing the local transmission of form data via Javascript: A Step-by-Step guide

Currently studying how to send forms using JavaScript by manually creating an XMLHttpRequest. Towards the end of the provided example, there's a note: Note: If you want to send data to a third party website, keep in mind that this use of XMLHttpRequ ...

A guide on extracting information from a personal Flask JSON route endpoint with Axios

I am looking to store JSON data in a variable using Axios in Javascript. The JSON endpoint is generated by my own server's route http://123.4.5.6:7890/json. I have been successful with this function: async function getClasses() { const res = await ...

Is there a way to update a JSON Array in PHP by replacing the existing data with the new data?

I am working with a JSON file and have encountered an issue when trying to delete an object. Whenever I create a new array and write it back to the original JSON file, the new data ends up overwriting the entire file. I have tried using functions like arr ...

Tips for exporting 3D objects from 3ds Max Studio for optimal use in Three.js

I am facing an issue with loading a 3D object that I created in 3D Studio Max! When I export it as a .obj file (which generates two files, .obj and .mtl), I have tried using OBJMTLLOADET(), MTLLOADER(), and OBJLOADER() but none of them seem to work. Other ...

"Trouble arises when attempting to include tables in the as_json

These are the models I am working with. class User < ActiveRecord::Base has_many :kriya_sessions end class KriyaSession < ActiveRecord::Base belongs_to :user end In my users controller, I am attempting to do the following: def user_sessions ...

Express (generator) is failing to load custom scripts located in the public folder

I'm new to node and express and I'm facing a problem. I want to load a custom script.js from the public folder, but it's not loading. There are no errors in the console or anything in the network tab. When I try to access the URL localhost:3 ...

Uniqid in React fails to generate unique IDs

Currently working on creating my first react project and developing a todo list. I have incorporated the uniqid generator into my todo object, but it seems to be returning an empty id rather than a random one. Oddly enough, if I move the todo state outsi ...