简体   繁体   English

JavaScript对象为JSON Node-RED

[英]JavaScript object to JSON Node-RED

I'm trying to pass a java script object generated by my red node flow to JSON format. 我正在尝试将我的红色节点流生成的Java脚本对象传递给JSON格式。 But it is causing me difficulty in knowing how to do it. 但这使我很难知道该怎么做。 The object script that is obtained is an hour and minute that is written on the screen for example "13:02". 获得的对象脚本是一个小时和分钟,例如在屏幕上写入的“ 13:02”。 In the "result" screen I need to see in JSON format 在“结果”屏幕中,我需要以JSON格式查看

{"time": "hh: mm"}

But I get "hh:mm" on the screen but i think not in json. 但是我在屏幕上看到“ hh:mm”,但我认为不是json。

Also when I submit the URL to a client web service and I try to check it the result in JSON I get this error: There was an error parsing JSON data 另外,当我将URL提交到客户端Web服务时,我尝试检查JSON中的结果时,也会出现此错误: 解析JSON数据时出错

This is the code: 这是代码:

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 show me it is s string: 调试消息告诉我它是s字符串:

在此处输入图片说明

If you want to return a JSON object then you shouldn't be using the JSON.stringify() function at all. 如果要返回JSON对象,则根本不应该使用JSON.stringify()函数。 Just assemble the object you want 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) {
  var hour = '0'+hour;
}
if(minute.toString().length == 1) {
  var minute = '0'+minute;
}
msg.payload = {
  "time": hour+':'+minute
}
return msg;

Also if you do need to convert objects to strings and vice versa us the JSON node from the pallet which converts msg.payload . 另外,如果确实需要将对象转换为字符串,反之亦然,请使用托盘中的JSON节点转换msg.payload

在此处输入图片说明

Assign the result to a variable. 将结果分配给变量。 JSON.stringify will return you a new object: msg will not be affected JSON.stringify将返回一个新对象: msg将不受影响

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

Example

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM