how to stop setInterval in JS in node-red..? - javascript

I'm trying to code a function node in node-red which will give output as increasing numbers by 1 for every second when get msg.paylaod true from inject node and stop when get msg.payload "false" from another inject node.
it starts giving output but don't stop when payload "false" is injected.
Node code:
[
{
"id":"b6c9b219.90a478",
"type":"function",
"z":"a3d6aff.bd4935",
"name":"",
"func":"var i = 1;\nfunction increment(){\n i = i + 1;\n msg={payload:i};\n node.send(msg);\n \n}\nif(msg.payload===true){\nvar interval = setInterval( increment, 1000);\nif(msg.payload===false){\n clearInterval(interval);\n}\n}\n\n",
"outputs":1,
"noerr":0,
"x":700.5,
"y":581,
"wires":[
[
"12f2090c.587347"
]
]
},
{
"id":"12f2090c.587347",
"type":"debug",
"z":"a3d6aff.bd4935",
"name":"",
"active":true,
"tosidebar":true,
"console":false,
"tostatus":false,
"complete":"true",
"x":826.5,
"y":473,
"wires":[
]
},
{
"id":"26abbbf.05cf944",
"type":"inject",
"z":"a3d6aff.bd4935",
"name":"",
"topic":"",
"payload":"true",
"payloadType":"bool",
"repeat":"",
"crontab":"",
"once":false,
"onceDelay":0.1,
"x":654.88330078125,
"y":767.2833251953125,
"wires":[
[
"b6c9b219.90a478"
]
]
},
{
"id":"880341a0.dcab2",
"type":"inject",
"z":"a3d6aff.bd4935",
"name":"",
"topic":"",
"payload":"false",
"payloadType":"bool",
"repeat":"",
"crontab":"",
"once":false,
"onceDelay":0.1,
"x":643.88330078125,
"y":824.0999755859375,
"wires":[
[
"b6c9b219.90a478"
]
]
}
]
Code of function node:
var i = 1;
function increment(){
i = i + 1;
msg={value:i};
node.send(msg);
if(msg.payload===false){
clearInterval(interval);
}
}
if(msg.payload===true){
var interval = setInterval( increment, 1000);
}

The short answer is you don't (easily).
The better way to do this is by having the function send all the messages in the sequence at once using the format for sending multiple messages. Then use the delay node to rate limit the stream so the messages are released once a second.
If you REALLY need (you really don't) to do it the way you have it then you need to save the internal timer in the context and retrieve it in the increment function to call clearInterval() on it.

I solved it like this. please take look at my node code. also please suggest if it can be done some other better way.
[
{
"id": "b6c9b219.90a478",
"type": "function",
"z": "a3d6aff.bd4935",
"name": "",
"func": "var i = 0;\nfunction increment(){\n i = i + 1;\n msg={value:i};\n node.send(msg);\n if(global.get(\"a\")===\"off\"){\n clearInterval(interval);\n }\n}\n\nif(msg.payload===true){\nvar interval = setInterval( increment, 1000);\n}",
"outputs": 1,
"noerr": 0,
"x": 450.5000305175781,
"y": 508,
"wires": [
[
"12f2090c.587347"
]
]
},
{
"id": "12f2090c.587347",
"type": "debug",
"z": "a3d6aff.bd4935",
"name": "",
"active": true,
"tosidebar": true,
"console": false,
"tostatus": false,
"complete": "true",
"x": 699.5,
"y": 686.9999694824219,
"wires": []
},
{
"id": "26abbbf.05cf944",
"type": "inject",
"z": "a3d6aff.bd4935",
"name": "",
"topic": "",
"payload": "true",
"payloadType": "bool",
"repeat": "",
"crontab": "",
"once": false,
"onceDelay": 0.1,
"x": 305.8833312988281,
"y": 430.2833557128906,
"wires": [
[
"b6c9b219.90a478",
"4fdb56dd.8ef"
]
]
},
{
"id": "880341a0.dcab2",
"type": "inject",
"z": "a3d6aff.bd4935",
"name": "",
"topic": "",
"payload": "false",
"payloadType": "bool",
"repeat": "",
"crontab": "",
"once": false,
"onceDelay": 0.1,
"x": 207.88333129882812,
"y": 666.0999450683594,
"wires": [
[
"4fdb56dd.8ef",
"b6c9b219.90a478"
]
]
},
{
"id": "4fdb56dd.8ef",
"type": "function",
"z": "a3d6aff.bd4935",
"name": "",
"func": "if(msg.payload===false){\n global.set(\"a\",\"off\");\n}\nif (msg.payload===true){\n global.set(\"a\",\"on\");\n}\nmsg={payload:global.get(\"a\")}\nreturn msg;",
"outputs": 1,
"noerr": 0,
"x": 202.26666259765625,
"y": 554.2332458496094,
"wires": [
[]
]
}
]

Related

How to select some properties from a json result

I am trying to build a simple react app which lists my philips hue bulb name and state(on or off). I have API call which results in the following json. Not sure how to pull bulb name and state.on status.
Here is my json result which gets the list of bulbs connected to my hue bridge. I get this result when i fetch via a the philips hue API.
{
"1": {
"state": {
"on": false,
"bri": 254,
"hue": 50116,
"sat": 248,
"effect": "none",
"xy": [
0.2444,
0.0969
],
"ct": 500,
"alert": "select",
"colormode": "xy",
"mode": "homeautomation",
"reachable": true
},
"swupdate": {
"state": "noupdates",
"lastinstall": "2021-08-19T18:10:44"
},
"type": "Extended color light",
"name": "TV 2",
"modelid": "LCT016",
"manufacturername": "Signify Netherlands B.V.",
"productname": "Hue color lamp",
"capabilities": {
"certified": true,
"control": {
"mindimlevel": 1000,
"maxlumen": 800,
"colorgamuttype": "C",
"colorgamut": [
[
0.6915,
0.3083
],
[
0.1700,
0.7000
],
[
0.1532,
0.0475
]
],
"ct": {
"min": 153,
"max": 500
}
},
"streaming": {
"renderer": true,
"proxy": true
}
},
"config": {
"archetype": "sultanbulb",
"function": "mixed",
"direction": "omnidirectional",
"startup": {
"mode": "safety",
"configured": true
}
},
"uniqueid": "00:17:88:01:03:db:75:df-0b",
"swversion": "1.88.1",
"swconfigid": "47ACF9B2",
"productid": "Philips-LCT016-1-A19ECLv5"
},
"2": {
"state": {
"on": false,
"bri": 254,
"hue": 8417,
"sat": 140,
"effect": "none",
"xy": [
0.4573,
0.4100
],
"ct": 366,
"alert": "select",
"colormode": "ct",
"mode": "homeautomation",
"reachable": true
},
"swupdate": {
"state": "noupdates",
"lastinstall": "2021-08-19T18:10:39"
},
"type": "Extended color light",
"name": "Study",
"modelid": "LCT016",
"manufacturername": "Signify Netherlands B.V.",
"productname": "Hue color lamp",
"capabilities": {
"certified": true,
"control": {
"mindimlevel": 1000,
"maxlumen": 800,
"colorgamuttype": "C",
"colorgamut": [
[
0.6915,
0.3083
],
[
0.1700,
0.7000
],
[
0.1532,
0.0475
]
],
"ct": {
"min": 153,
"max": 500
}
},
"streaming": {
"renderer": true,
"proxy": true
}
},
"config": {
"archetype": "sultanbulb",
"function": "mixed",
"direction": "omnidirectional",
"startup": {
"mode": "safety",
"configured": true
}
},
"uniqueid": "00:17:88:01:03:94:fa:07-0b",
"swversion": "1.88.1",
"swconfigid": "47ACF9B2",
"productid": "Philips-LCT016-1-A19ECLv5"
}
}
You can map them into an array using map(). Since map only works on arrays, and your data is an object, you can use Object.values to return an array of the object's values and use map on that, like this:
const data={1:{state:{on:!1,bri:254,hue:50116,sat:248,effect:"none",xy:[.2444,.0969],ct:500,alert:"select",colormode:"xy",mode:"homeautomation",reachable:!0},swupdate:{state:"noupdates",lastinstall:"2021-08-19T18:10:44"},type:"Extended color light",name:"TV 2",modelid:"LCT016",manufacturername:"Signify Netherlands B.V.",productname:"Hue color lamp",capabilities:{certified:!0,control:{mindimlevel:1e3,maxlumen:800,colorgamuttype:"C",colorgamut:[[.6915,.3083],[.17,.7],[.1532,.0475]],ct:{min:153,max:500}},streaming:{renderer:!0,proxy:!0}},config:{archetype:"sultanbulb",function:"mixed",direction:"omnidirectional",startup:{mode:"safety",configured:!0}},uniqueid:"00:17:88:01:03:db:75:df-0b",swversion:"1.88.1",swconfigid:"47ACF9B2",productid:"Philips-LCT016-1-A19ECLv5"},2:{state:{on:!1,bri:254,hue:8417,sat:140,effect:"none",xy:[.4573,.41],ct:366,alert:"select",colormode:"ct",mode:"homeautomation",reachable:!0},swupdate:{state:"noupdates",lastinstall:"2021-08-19T18:10:39"},type:"Extended color light",name:"Study",modelid:"LCT016",manufacturername:"Signify Netherlands B.V.",productname:"Hue color lamp",capabilities:{certified:!0,control:{mindimlevel:1e3,maxlumen:800,colorgamuttype:"C",colorgamut:[[.6915,.3083],[.17,.7],[.1532,.0475]],ct:{min:153,max:500}},streaming:{renderer:!0,proxy:!0}},config:{archetype:"sultanbulb",function:"mixed",direction:"omnidirectional",startup:{mode:"safety",configured:!0}},uniqueid:"00:17:88:01:03:94:fa:07-0b",swversion:"1.88.1",swconfigid:"47ACF9B2",productid:"Philips-LCT016-1-A19ECLv5"}};
let bulbs = Object.values(data).map(
m=>{return {name: m.name, state: m.state.on}}
);
console.log(bulbs);

How can I extract a key with different values?

I have several same keys and multiple values I just want to parse JSON with keys and values and extract device_id, As you can see all device_id is the same but the value of them is different.
How can I parse.json and have just device_id: values?
My file is like this :
[
{
"id": "c19ca393.e14b1",
"type": "tab",
"label": "Flow 1",
"disabled": false,
"info": ""
},
{
"id": "a15871bb.7c3b2",
"type": "input-distributer",
"z": "c19ca393.e14b1",
"name": "input-distributer",
"device_id": "93e71ba7-fb56-5592-a5f6-d855203dd7ae",
"device_name": "nmos-cpp_node_10-20-130-24:6131",
"x": 280,
"y": 260,
"wires": [
[
"6548d2cb.45bc1c"
],
[
"7cf8bc7e.204a84"
]
]
},
{
"id": "421da76b.670be8",
"type": "output-distributer",
"z": "c19ca393.e14b1",
"name": "output-distributer",
"device_id": "93e71ba7-fb56-5592-a5f6-d855203dd7ae",
"device_name": "nmos-cpp_node_10-20-130-24:6131",
"x": 620,
"y": 260,
"wires": [
]
},
{
"id": "6548d2cb.45bc1c",
"type": "video-switcher",
"z": "c19ca393.e14b1",
"name": "video-switcher",
"device_id": "93e71ba7-fb56-5592-a5f6-d855203dd7ae",
"device_name": "nmos-cpp_node_10-20-130-24:6131",
"x": 480,
"y": 120,
"wires": [
[
"421da76b.670be8"
]
]
},
{
"id": "7cf8bc7e.204a84",
"type": "audio-switcher",
"z": "c19ca393.e14b1",
"name": "audio-switcher",
"device_id": "fe21abdf-706f-5c7b-adb8-2507e145e820",
"device_name": "nmos-cpp_node_10-20-130-24:6121",
"x": 440,
"y": 360,
"wires": [
[
"421da76b.670be8"
]
]
}
]
If I wanted to grab all the values of the device id, How is it possible?
You can try this for getting device_id values
data.map(element => { // data refers to your array
console.log(element['device_id']);
});
since in first object device_id is not there so it will print undefined and you can apply a check on that.
You can add a check if device_id exists or not and the you can .map it.
Try this:
let arr = [{"id":"c19ca393.e14b1","type":"tab","label":"Flow 1","disabled":false,"info":""},{"id":"a15871bb.7c3b2","type":"input-distributer","z":"c19ca393.e14b1","name":"input-distributer","device_id":"93e71ba7-fb56-5592-a5f6-d855203dd7ae","device_name":"nmos-cpp_node_10-20-130-24:6131","audio_services":"{\"node-input-audio_services1\":\"c250498b-52ee-5162-b450-e15905912e8c\",\"audio_ip_1\":\"1.2.3.4\",\"audio_port_1\":\"1234\"}","video_services":"{\"node-input-video_services1\":\"c250498b-52ee-5162-b450-e15905912e8c\",\"video_ip_1\":\"5.6.7.8\",\"video_port_1\":\"5678\"}","x":280,"y":260,"wires":[["6548d2cb.45bc1c"],["7cf8bc7e.204a84"]]},{"id":"421da76b.670be8","type":"output-distributer","z":"c19ca393.e14b1","name":"output-distributer","device_id":"93e71ba7-fb56-5592-a5f6-d855203dd7ae","device_name":"nmos-cpp_node_10-20-130-24:6131","audio_services":"{\"node-input-audio_services1\":\"7d010b65-b9d8-5561-a622-189b1c06d3f9\"}","video_services":"{\"node-input-video_services1\":\"7d010b65-b9d8-5561-a622-189b1c06d3f9\"}","x":620,"y":260,"wires":[]},{"id":"6548d2cb.45bc1c","type":"video-switcher","z":"c19ca393.e14b1","name":"video-switcher","device_id":"93e71ba7-fb56-5592-a5f6-d855203dd7ae","device_name":"nmos-cpp_node_10-20-130-24:6131","video_senders":"{\"node-input-senders_services1\":\"c250498b-52ee-5162-b450-e15905912e8c\",\"senders_ip_1\":\"9.0.1.2\",\"senders_port_1\":\"9012\"}","video_receivers":"{\"node-input-receivers_services1\":\"7d010b65-b9d8-5561-a622-189b1c06d3f9\"}","x":480,"y":120,"wires":[["421da76b.670be8"]]},{"id":"7cf8bc7e.204a84","type":"audio-switcher","z":"c19ca393.e14b1","name":"audio-switcher","device_id":"fe21abdf-706f-5c7b-adb8-2507e145e820","device_name":"nmos-cpp_node_10-20-130-24:6121","audio_senders":"{\"node-input-senders_services1\":\"7408e1be-a227-5d0a-a22b-294bcf22017c\",\"senders_ip_1\":\"0.0.0.0\",\"senders_port_1\":\"0000\"}","audio_receivers":"{\"node-input-receivers_services1\":\"d08f3a50-41fc-5020-9c6c-175d91891aef\"}","x":440,"y":360,"wires":[["421da76b.670be8"]]}]
let device_ids = arr.filter(o => o.device_id).map(obj => obj.device_id);
console.log(device_ids);
After you opened the file and get the data from it, iterate through array and check if object has property device_id obj.hasOwnProperty("device_id") , if it's present, print it:
// edit after comment ---------
async function getFileContent() {
fs.readFile("flow_demo_1.json", (err, data) => {
if (err) {
console.log(err);
} else {
console.log(data.toString());
return data
}
})
}
// const fileContent = await getFileContent();
// const myObj = JSON.parse(fileContent)
// ---------
const myObj = [{
"id": "c19ca393.e14b1",
"type": "tab",
"label": "Flow 1",
"disabled": false,
"info": ""
},
{
"id": "a15871bb.7c3b2",
"type": "input-distributer",
"z": "c19ca393.e14b1",
"name": "input-distributer",
"device_id": "93e71ba7-fb56-5592-a5f6-d855203dd7ae",
"device_name": "nmos-cpp_node_10-20-130-24:6131",
"audio_services": "{\"node-input-audio_services1\":\"c250498b-52ee-5162-b450-e15905912e8c\",\"audio_ip_1\":\"1.2.3.4\",\"audio_port_1\":\"1234\"}",
"video_services": "{\"node-input-video_services1\":\"c250498b-52ee-5162-b450-e15905912e8c\",\"video_ip_1\":\"5.6.7.8\",\"video_port_1\":\"5678\"}",
"x": 280,
"y": 260,
"wires": [
[
"6548d2cb.45bc1c"
],
[
"7cf8bc7e.204a84"
]
]
},
{
"id": "421da76b.670be8",
"type": "output-distributer",
"z": "c19ca393.e14b1",
"name": "output-distributer",
"device_id": "93e71ba7-fb56-5592-a5f6-d855203dd7ae",
"device_name": "nmos-cpp_node_10-20-130-24:6131",
"audio_services": "{\"node-input-audio_services1\":\"7d010b65-b9d8-5561-a622-189b1c06d3f9\"}",
"video_services": "{\"node-input-video_services1\":\"7d010b65-b9d8-5561-a622-189b1c06d3f9\"}",
"x": 620,
"y": 260,
"wires": [
]
},
{
"id": "6548d2cb.45bc1c",
"type": "video-switcher",
"z": "c19ca393.e14b1",
"name": "video-switcher",
"device_id": "93e71ba7-fb56-5592-a5f6-d855203dd7ae",
"device_name": "nmos-cpp_node_10-20-130-24:6131",
"video_senders": "{\"node-input-senders_services1\":\"c250498b-52ee-5162-b450-e15905912e8c\",\"senders_ip_1\":\"9.0.1.2\",\"senders_port_1\":\"9012\"}",
"video_receivers": "{\"node-input-receivers_services1\":\"7d010b65-b9d8-5561-a622-189b1c06d3f9\"}",
"x": 480,
"y": 120,
"wires": [
[
"421da76b.670be8"
]
]
},
{
"id": "7cf8bc7e.204a84",
"type": "audio-switcher",
"z": "c19ca393.e14b1",
"name": "audio-switcher",
"device_id": "fe21abdf-706f-5c7b-adb8-2507e145e820",
"device_name": "nmos-cpp_node_10-20-130-24:6121",
"audio_senders": "{\"node-input-senders_services1\":\"7408e1be-a227-5d0a-a22b-294bcf22017c\",\"senders_ip_1\":\"0.0.0.0\",\"senders_port_1\":\"0000\"}",
"audio_receivers": "{\"node-input-receivers_services1\":\"d08f3a50-41fc-5020-9c6c-175d91891aef\"}",
"x": 440,
"y": 360,
"wires": [
[
"421da76b.670be8"
]
]
}
]
for (let obj of myObj) {
if (obj.hasOwnProperty("device_id")) {
console.log("device_id: " + obj.device_id)
}
}
finally found my answer :
var fileContent = fs.readFileSync('flow_demo_1.json', 'utf8');
console.log(fileContent);
const myObj = JSON.parse(fileContent)
for (let obj of myObj) {
if (obj.hasOwnProperty("device_id")) {
console.log("device_id: " + obj.device_id);
}
}
Thanks every one.

Node-RED Sending multiple msg only returning first msg

I'm trying to send multiple messages using NodeRed.
I've tried two options: Trying to send using one output, and trying to send using two outputs.
Processing1 code:
var msg1 = {};
var msg2 = {};
msg1.topic = "fooTopic1";
msg2.topic = "barTopic1";
msg1.payload = "fooLoad1";
msg2.payload = "barLoad1";
return [msg1,msg2];
Result:
Processing2 code:
var msg1 = {};
var msg2 = {};
msg1.topic = "fooTopic2";
msg2.topic = "barTopic2";
msg1.payload = "fooLoad2";
msg2.payload = "barLoad2";
return msg1,msg2;
I was expecting 2 seperate messages, but debug only outputs one.
What am I doing wrong?
Flow for those who want to test for themselves:
[
{
"id": "5824c01b.a28ab",
"type": "tab",
"label": "Flow 2",
"disabled": false,
"info": ""
},
{
"id": "4902c067.f3c27",
"type": "inject",
"z": "5824c01b.a28ab",
"name": "Input",
"topic": "",
"payload": "",
"payloadType": "date",
"repeat": "",
"crontab": "",
"once": false,
"onceDelay": 0.1,
"x": 150,
"y": 220,
"wires": [
[
"6a361af6.b5edf4"
]
]
},
{
"id": "6a361af6.b5edf4",
"type": "function",
"z": "5824c01b.a28ab",
"name": "Processing2",
"func": "var msg1 = {};\nvar msg2 = {};\n\nmsg1.topic = \"fooTopic2\";\nmsg2.topic = \"barTopic2\";\n\nmsg1.payload = \"fooLoad2\";\nmsg2.payload = \"barLoad2\";\n\nreturn msg1,msg2;",
"outputs": 2,
"noerr": 0,
"x": 350,
"y": 220,
"wires": [
[
"727ebca3.2270a4"
],
[
"727ebca3.2270a4"
]
]
},
{
"id": "727ebca3.2270a4",
"type": "debug",
"z": "5824c01b.a28ab",
"name": "",
"active": true,
"tosidebar": true,
"console": false,
"tostatus": false,
"complete": "true",
"targetType": "full",
"x": 530,
"y": 220,
"wires": []
},
{
"id": "6b1d928e.2752bc",
"type": "inject",
"z": "5824c01b.a28ab",
"name": "Input",
"topic": "",
"payload": "",
"payloadType": "date",
"repeat": "",
"crontab": "",
"once": false,
"onceDelay": 0.1,
"x": 150,
"y": 160,
"wires": [
[
"cc02ad73.9febe"
]
]
},
{
"id": "cc02ad73.9febe",
"type": "function",
"z": "5824c01b.a28ab",
"name": "Processing1",
"func": "var msg1 = {};\nvar msg2 = {};\n\nmsg1.topic = \"fooTopic1\";\nmsg2.topic = \"barTopic1\";\n\nmsg1.payload = \"fooLoad1\";\nmsg2.payload = \"barLoad1\";\n\nreturn [msg1,msg2];",
"outputs": 1,
"noerr": 0,
"x": 350,
"y": 160,
"wires": [
[
"a8e66620.492e48"
]
]
},
{
"id": "a8e66620.492e48",
"type": "debug",
"z": "5824c01b.a28ab",
"name": "",
"active": true,
"tosidebar": true,
"console": false,
"tostatus": false,
"complete": "true",
"targetType": "full",
"x": 530,
"y": 160,
"wires": []
}
]
Node-RED v.0.20.7
This is because function nodes can have multiple output ports.
To send multiple messages out of a single output port you need to double wrap the messages in square brackets.
return [[msg1,msg2]]
This is because a single array tells Node-RED to send msg1 from the first port and msg2 from the second port.
Using a 2D array says send msg1 & msg2 from port 1.
It depends on your needs. Do you want to send multiple messages to different destinations or to the same destination?
(A) Multiple messages, different destinations
You need to set multiple outputs (e.g. two outputs), and use return [msg1,msg2];. Full code:
var msg1 = {};
var msg2 = {};
msg1.topic = "fooTopicA";
msg2.topic = "barTopicA";
msg1.payload = "fooLoadA";
msg2.payload = "barLoadA";
return [msg1,msg2];
(B) Multiple messages, single destination
You don't need to set multiple outputs, you need just one. In your function node use return [[msg1,msg2]];. Full code:
var msg1 = {};
var msg2 = {};
msg1.topic = "fooTopicB";
msg2.topic = "barTopicB";
msg1.payload = "fooLoadB";
msg2.payload = "barLoadB";
return [[msg1,msg2]];
Full flow for testing:
[{"id":"5da1a303.2f8bbc","type":"tab","label":"test","disabled":false,"info":""},{"id":"2b48081b.61be58","type":"inject","z":"5da1a303.2f8bbc","name":"Input","repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"","payloadType":"date","x":170,"y":300,"wires":[["c7169d64.37036"]]},{"id":"c7169d64.37036","type":"function","z":"5da1a303.2f8bbc","name":"Processing B","func":"var msg1 = {};\nvar msg2 = {};\n\nmsg1.topic = \"fooTopicB\";\nmsg2.topic = \"barTopicB\";\n\nmsg1.payload = \"fooLoadB\";\nmsg2.payload = \"barLoadB\";\n\nreturn [[msg1,msg2]];","outputs":1,"noerr":0,"initialize":"","finalize":"","x":370,"y":300,"wires":[["6b11270f.3477a8"]]},{"id":"6b11270f.3477a8","type":"debug","z":"5da1a303.2f8bbc","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"true","targetType":"full","x":550,"y":300,"wires":[]},{"id":"6cd03253.f1e09c","type":"inject","z":"5da1a303.2f8bbc","name":"Input","repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"","payloadType":"date","x":170,"y":180,"wires":[["d9b50766.e9c9a8"]]},{"id":"d9b50766.e9c9a8","type":"function","z":"5da1a303.2f8bbc","name":"Processing A","func":"var msg1 = {};\nvar msg2 = {};\n\nmsg1.topic = \"fooTopicA\";\nmsg2.topic = \"barTopicA\";\n\nmsg1.payload = \"fooLoadA\";\nmsg2.payload = \"barLoadA\";\n\nreturn [msg1,msg2];","outputs":2,"noerr":0,"initialize":"","finalize":"","x":370,"y":180,"wires":[["abde843d.cbf888"],["e99faf37.fe8b3"]]},{"id":"abde843d.cbf888","type":"debug","z":"5da1a303.2f8bbc","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"true","targetType":"full","x":550,"y":160,"wires":[]},{"id":"e99faf37.fe8b3","type":"debug","z":"5da1a303.2f8bbc","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"true","targetType":"full","x":550,"y":220,"wires":[]}]

Need to get Name, Node Name and Phase Values from API

I am trying to get Name, Node Name and Phase values from JSON Data using JavaScript. Here is my JavaScript
<script>
$(document).ready(function () {
$.getJSON('http://ec2-3-82-117-70.compute-1.amazonaws.com:8080/api/v0/retrievePodStatus/default',
function (data) {
console.log(data)
document.body.append("Name: " + data.items[1].metadata.name);
// document.body.append(data.items[1].metadata.name);
// document.body.append(data.items[0].spec.nodeName);
});
});
</script>
I am just getting the name in here. Can someone please help me how to get Name, Node Name and Phase Values? find the below JSON as well.
"apiVersion": "v1",
"items": [
{
"apiVersion": "v1",
"kind": "Pod",
"metadata": {
"annotations": {
"kubernetes.io/limit-ranger": "LimitRanger plugin set: cpu request for container external-dns"
},
"creationTimestamp": "2019-02-28T16:22:49Z",
"generateName": "external-dns-5d69b66646-",
"labels": {
"app": "external-dns",
"pod-template-hash": "1825622202"
},
"name": "external-dns-5d69b66646-pmxmd",
"namespace": "default",
"ownerReferences": [
{
"apiVersion": "extensions/v1beta1",
"blockOwnerDeletion": true,
"controller": true,
"kind": "ReplicaSet",
"name": "external-dns-5d69b66646",
"uid": "170d9260-3b75-11e9-abe2-0ec5819342ce"
}
],
"resourceVersion": "2984",
"selfLink": "/api/v1/namespaces/default/pods/external-dns-5d69b66646-pmxmd",
"uid": "170e1a0d-3b75-11e9-abe2-0ec5819342ce"
},
"spec": {
"containers": [
{
"args": [
"--source=service",
"--source=ingress",
"--provider=aws",
"--registry=txt",
"--txt-owner-id=qpair"
],
"image": "registry.opensource.zalan.do/teapot/external-dns:v0.4.2",
"imagePullPolicy": "IfNotPresent",
"name": "external-dns",
"resources": {
"requests": {
"cpu": "100m"
}
},
"terminationMessagePath": "/dev/termination-log",
"terminationMessagePolicy": "File",
"volumeMounts": [
{
"mountPath": "/var/run/secrets/kubernetes.io/serviceaccount",
"name": "default-token-rr546",
"readOnly": true
}
]
}
],
"dnsPolicy": "ClusterFirst",
"nodeName": "ip-172-20-39-147.ec2.internal",
"restartPolicy": "Always",
"schedulerName": "default-scheduler",
"securityContext": {},
"serviceAccount": "default",
"serviceAccountName": "default",
"terminationGracePeriodSeconds": 30,
"tolerations": [
{
"effect": "NoExecute",
"key": "node.kubernetes.io/not-ready",
"operator": "Exists",
"tolerationSeconds": 300
},
{
"effect": "NoExecute",
"key": "node.kubernetes.io/unreachable",
"operator": "Exists",
"tolerationSeconds": 300
}
],
"volumes": [
{
"name": "default-token-rr546",
"secret": {
"defaultMode": 420,
"secretName": "default-token-rr546"
}
}
]
},
"status": {
"conditions": [
{
"lastProbeTime": null,
"lastTransitionTime": "2019-02-28T16:22:49Z",
"status": "True",
"type": "Initialized"
},
{
"lastProbeTime": null,
"lastTransitionTime": "2019-02-28T16:22:58Z",
"status": "True",
"type": "Ready"
},
{
"lastProbeTime": null,
"lastTransitionTime": "2019-02-28T16:22:49Z",
"status": "True",
"type": "PodScheduled"
}
],
"containerStatuses": [
{
"containerID": "docker://18b96317cf360d562fb3f849c6716c50a41a67a4dbc126164020531e1e4d84a9",
"image": "registry.opensource.zalan.do/teapot/external-dns:v0.4.2",
"imageID": "docker-pullable://registry.opensource.zalan.do/teapot/external-dns#sha256:d54b9eb8948b87eb7fcd938990ff2dbc9ca0a42d9c5d36fcaa75c7cf066f7995",
"lastState": {},
"name": "external-dns",
"ready": true,
"restartCount": 0,
"state": {
"running": {
"startedAt": "2019-02-28T16:22:57Z"
}
}
}
],
"hostIP": "172.20.39.147",
"phase": "Running",
"podIP": "100.96.7.3",
"qosClass": "Burstable",
"startTime": "2019-02-28T16:22:49Z"
}
},
I am just getting the name in here. Can someone please help me how to get Name, Node Name and Phase Values? find the below JSON as well.
Thanks, Much Appreciated
You were close with the code you posted. You just needed items[0] instead of items[1]. Remember the first element of an array is always 0. Other than that its as easy as checking the open and close brackets [] or {} to see where each nested object/array starts and ends.
Code:
var name = data.items[0].metadata.name
var nodeName = data.items[0].spec.nodeName
var phase = data.items[0].status.phase
snippet:
var data = {
"apiVersion": "v1",
"items": [{
"apiVersion": "v1",
"kind": "Pod",
"metadata": {
"annotations": {
"kubernetes.io/limit-ranger": "LimitRanger plugin set: cpu request for container external-dns"
},
"creationTimestamp": "2019-02-28T16:22:49Z",
"generateName": "external-dns-5d69b66646-",
"labels": {
"app": "external-dns",
"pod-template-hash": "1825622202"
},
"name": "external-dns-5d69b66646-pmxmd",
"namespace": "default",
"ownerReferences": [{
"apiVersion": "extensions/v1beta1",
"blockOwnerDeletion": true,
"controller": true,
"kind": "ReplicaSet",
"name": "external-dns-5d69b66646",
"uid": "170d9260-3b75-11e9-abe2-0ec5819342ce"
}],
"resourceVersion": "2984",
"selfLink": "/api/v1/namespaces/default/pods/external-dns-5d69b66646-pmxmd",
"uid": "170e1a0d-3b75-11e9-abe2-0ec5819342ce"
},
"spec": {
"containers": [{
"args": [
"--source=service",
"--source=ingress",
"--provider=aws",
"--registry=txt",
"--txt-owner-id=qpair"
],
"image": "registry.opensource.zalan.do/teapot/external-dns:v0.4.2",
"imagePullPolicy": "IfNotPresent",
"name": "external-dns",
"resources": {
"requests": {
"cpu": "100m"
}
},
"terminationMessagePath": "/dev/termination-log",
"terminationMessagePolicy": "File",
"volumeMounts": [{
"mountPath": "/var/run/secrets/kubernetes.io/serviceaccount",
"name": "default-token-rr546",
"readOnly": true
}]
}],
"dnsPolicy": "ClusterFirst",
"nodeName": "ip-172-20-39-147.ec2.internal",
"restartPolicy": "Always",
"schedulerName": "default-scheduler",
"securityContext": {},
"serviceAccount": "default",
"serviceAccountName": "default",
"terminationGracePeriodSeconds": 30,
"tolerations": [{
"effect": "NoExecute",
"key": "node.kubernetes.io/not-ready",
"operator": "Exists",
"tolerationSeconds": 300
},
{
"effect": "NoExecute",
"key": "node.kubernetes.io/unreachable",
"operator": "Exists",
"tolerationSeconds": 300
}
],
"volumes": [{
"name": "default-token-rr546",
"secret": {
"defaultMode": 420,
"secretName": "default-token-rr546"
}
}]
},
"status": {
"conditions": [{
"lastProbeTime": null,
"lastTransitionTime": "2019-02-28T16:22:49Z",
"status": "True",
"type": "Initialized"
},
{
"lastProbeTime": null,
"lastTransitionTime": "2019-02-28T16:22:58Z",
"status": "True",
"type": "Ready"
},
{
"lastProbeTime": null,
"lastTransitionTime": "2019-02-28T16:22:49Z",
"status": "True",
"type": "PodScheduled"
}
],
"containerStatuses": [{
"containerID": "docker://18b96317cf360d562fb3f849c6716c50a41a67a4dbc126164020531e1e4d84a9",
"image": "registry.opensource.zalan.do/teapot/external-dns:v0.4.2",
"imageID": "docker-pullable://registry.opensource.zalan.do/teapot/external-dns#sha256:d54b9eb8948b87eb7fcd938990ff2dbc9ca0a42d9c5d36fcaa75c7cf066f7995",
"lastState": {},
"name": "external-dns",
"ready": true,
"restartCount": 0,
"state": {
"running": {
"startedAt": "2019-02-28T16:22:57Z"
}
}
}],
"hostIP": "172.20.39.147",
"phase": "Running",
"podIP": "100.96.7.3",
"qosClass": "Burstable",
"startTime": "2019-02-28T16:22:49Z"
}
}],
}
var name = data.items[0].metadata.name
var nodeName = data.items[0].spec.nodeName
var phase = data.items[0].status.phase
console.log(name)
console.log(nodeName)
console.log(phase)

How can I transform a JSON array of object contained in one message to multiple JSON object messages?

currently creating an ETL flow running in Node-RED, running on Node.js, running on Bluemix running on CloudFoundry.
I'm querying a Cloudant DB and get the result of the query returned as on single JSON array containing all documents as JSON objects.
No I want to individually process those in a pipe-lined fashion. How can this be archieved in Node-RED?
Thanks a lot!
JSON
[{
"id": "c8342b2a.bf0df",
"type": "cloudant in",
"z": "2f0a54f6.110ccc",
"service": "nokeredrkie-cloudantNoSQLDB",
"cloudant": "",
"name": "",
"database": "tweets",
"search": "_all_",
"design": "",
"index": "",
"x": 295.70001220703125,
"y": 450.9333190917969,
"wires": [
["5e83a34.48cdd5c"]
]
}, {
"id": "c9411e75.2b1b7",
"type": "debug",
"z": "2f0a54f6.110ccc",
"name": "",
"active": true,
"console": "false",
"complete": "payload",
"x": 646.699951171875,
"y": 470.7333679199219,
"wires": []
}, {
"id": "3f1d2018.8f5ec8",
"type": "inject",
"z": "2f0a54f6.110ccc",
"name": "",
"topic": "",
"payload": "",
"payloadType": "date",
"repeat": "",
"crontab": "",
"once": true,
"x": 126.70001220703125,
"y": 472.6666564941406,
"wires": [
["c8342b2a.bf0df"]
]
}, {
"id": "5e83a34.48cdd5c",
"type": "function",
"z": "2f0a54f6.110ccc",
"name": "",
"func": "//msg.payload = JSON.parse(msg.payload);\nmsg.payload = msg.payload[1].tweet.user.screen_name;\nreturn msg;",
"outputs": 1,
"noerr": 0,
"x": 444.70001220703125,
"y": 489.4000549316406,
"wires": [
["c9411e75.2b1b7"]
]
}]
Output the Cloudant node to Function node with something like this:
var msgs = [];
for (var i = 0; i< msg.payload.length; i++) {
msgs.push({payload: msg.payload[i]});
}
return [msgs]
This will stream each item in the array to the next node in the flow
Edit: need to wrap the array in another set of [] to get all the messages out the same output.

Categories

Resources