Hi
i have some homey script’s running to work with some json api’s, thats ok.
but now i am attempting to retireve a value from a plane html/txt web page
i need to get the: motionDetectAlarm value
if there is a flowcard that can do the job i can use that instead
<CGI_Result>
<result>0</result>
<IOAlarm>0</IOAlarm>
<motionDetectAlarm>1</motionDetectAlarm>
<humanDetectAlarmState>0</humanDetectAlarmState>
<soundAlarm>0</soundAlarm>
<record>0</record>
<sdState>1</sdState>
<sdFreeSpace>120847040k</sdFreeSpace>
<sdTotalSpace>121739200k</sdTotalSpace>
<ntpState>0</ntpState>
<isWifiConnected>1</isWifiConnected>
<wifiConnectedAP>wifi</wifiConnectedAP>
<infraLedState>0</infraLedState>
</CGI_Result>
I found an online script, and fiddled with JSON.stringify()
and slice()
to filter on motionDetectAlarm
Further below is an Aflow homeyscript-card example
const xmlString = '<CGI_Result><result>0</result><IOAlarm>0</IOAlarm><motionDetectAlarm>1</motionDetectAlarm><humanDetectAlarmState>0</humanDetectAlarmState><soundAlarm>0</soundAlarm><record>0</record><sdState>1</sdState><sdFreeSpace>120847040k</sdFreeSpace><sdTotalSpace>121739200k</sdTotalSpace><ntpState>0</ntpState><isWifiConnected>1</isWifiConnected><wifiConnectedAP>wifi</wifiConnectedAP><infraLedState>0</infraLedState></CGI_Result>'; //provided xml
function convertXmlToJson(xmlString) {
const jsonData = {};
for (const result of xmlString.matchAll(/(?:<(\w*)(?:\s[^>]*)*>)((?:(?!<\1).)*)(?:<\/\1>)|<(\w*)(?:\s*)*\/>/gm)) {
const key = result[1] || result[3];
const value = result[2] && convertXmlToJson(result[2]); //recusrion
jsonData[key] = ((value && Object.keys(value).length) ? value : result[2]) || null;
}
return jsonData;
}
var motionDetectAlarmState
motionDetectAlarmState = JSON.stringify(convertXmlToJson(xmlString)).slice(42,65);
console.log(`{${motionDetectAlarmState}}`);
return(true);
.
Output:

.
-
This is an example of using an Aflow homeyscript card for this:
I used “Run code with argument and return text-tag”
Then the argument is the XML code
And the script:
// xml-2-json
const xmlString = args[0]; //provided xml
function convertXmlToJson(xmlString) {
const jsonData = {};
for (const result of xmlString.matchAll(/(?:<(\w*)(?:\s[^>]*)*>)((?:(?!<\1).)*)(?:<\/\1>)|<(\w*)(?:\s*)*\/>/gm)) {
const key = result[1] || result[3];
const value = result[2] && convertXmlToJson(result[2]); //recusrion
jsonData[key] = ((value && Object.keys(value).length) ? value : result[2]) || null;
}
return jsonData;
}
var motionDetectAlarmState
motionDetectAlarmState = JSON.stringify(convertXmlToJson(xmlString)).slice(42,65);
console.log(`{${motionDetectAlarmState}}`);
return(`{${String(motionDetectAlarmState)}}`);