I’m trying to parse a JSON and use it in a for each, therefore it needs to be an object and cant use transform("JSONPATH", ...).
When I use javascript JSON.parse(json) I get an error:
14:37:16.937 [ERROR] [.internal.handler.ScriptActionHandler] - Script execution of rule with UID 'rule-1' failed: The name 'JSON' cannot be resolved to an item or type; line 10, column 16, length 4 in rule
Cant javascript be used anymore? Do I need to import something?
when
Item Helium_Explorer_Witnessed received update
then
val json = (Helium_Explorer_Witnessed.state as StringType).toString
val data = JSON.parse(json)
end
That is fragment of file-based DSL rule syntax, but not a complete rule (missing rule "myrule"). Where are you putting it, exactly? DSL does not include a JSON utility. This is not javascript.
You can call javascript JS transforms from a DSL rule, but can only get a single string in return
Many people create javascript rules using GUI in OH3. This is a whole new method of working for you to learn. Or javascript rules may used in their own files based version.
Note that OH3 currently supports two different versions of javascript rules
Background -
If you want to stick with DSL, you might be more explicit about what you are trying to achieve. JSONPATH transformation has limitations, some can be worked around. Example
Ok digged a little deeper into your posts. I’m going to move all my DSL rules to UI JSScripting rules. Javascript is a much more understandable language for me.
I got it working in DSL do, for others:
val int numElements = Integer.parseInt(transform("JSONPATH", "$.data.length()", json))
logInfo("test", "There are {} elements in array", numElements)
var int i
for (i=0; i < numElements; i++) {
val name = transform("JSONPATH", "$.data.[" + i + "].name", json)
val time = transform("JSONPATH", "$.data.[" + i + "].time", json)
logInfo("helium", "time={}:{}", name, time)
}
But it’s very cluncy.
With javascript:
var json = JSON.parse(item);
json.data.forEach(function(row) {
console.log(row.name, row.time)
}