I trying to implement some rules to configure some scenes through a sitemap.
I am almost there but struggling with deleting an element from a JSON array.
I have this JSON which holds the configuration for my livingroom scenes
{
"ON" : [
{
"ItemName" : "z_l_table",
"Value" : "ON"
},
{
"ItemName" : "z_l_janine",
"Value" : "ON"
}
],
"OFF" : [
{
"ItemName" : "z_l_table",
"Value" : "OFF"
},
{
"ItemName" : "z_l_janine",
"Value" : "OFF"
}
],
"READ" : [
{
"ItemName" : "z_l_table",
"Value" : "30"
},
{
"ItemName" : "z_l_janine",
"Value" : "ON"
}
]
}
The elements “ON”, “OFF”, etc are the name of my scenes, the arrays nested below these elements are the lights and their target values for that scene.
What I am trying to do is to dynamically create the JSON.
In order to do so I need to
- delete the entry which was changed by the user, e.g. “ON”
- write the new “ON” entry to the JSON
I have the 2. step working but pulling my hair out with the delete part.
I am trying to use this javascript transformation RemoveNode.js
(function(i) {
var inputArray = i.split(" ");
var strJSON = inputArray[0];
var intIndex2Delete = inputArray[1];
strJSON.splice(intIndex2Delete,1);
return strJSON;
})(input)
This how I call the transformation from a test rule
rule "test_splice"
when
Item vsTest_2 changed from OFF to ON
then
var testJSON = '{
"ON" : [
{
"ItemName" : "z_l_table",
"Value" : "ON"
},
{
"ItemName" : "z_l_janine",
"Value" : "ON"
}
],
"OFF" : [
{
"ItemName" : "z_l_table",
"Value" : "OFF"
},
{
"ItemName" : "z_l_janine",
"Value" : "OFF"
}
],
"READ" : [
{
"ItemName" : "z_l_table",
"Value" : "30"
},
{
"ItemName" : "z_l_janine",
"Value" : "ON"
}
]
}'
var strNewJSON = transform("JS", "RemoveNode.js", testJSON+" 2")
logInfo( "sensor.rules", "test_splice: strNewJSON:"+strNewJSON)
end
This is the result in the log, the deletion was more successfull that I was hoping
2019-08-30 13:28:37.170 [INFO ] [.smarthome.model.script.sensor.rules] - test_splice: strNewJSON:{
Is there a better way to do this?
EDIT:
I now realize that the splitting of parameters in the .js function can obviously not work…
I tried splitting with a “|” character that is very unlikely to come up in my JSON,
but split is not working.
There HAS to be a better way…