I’ve got a partially working function, but it’s a bit funny. For some reason the call to cleanup the JSON is not liked, because it seem that the actual result is not returned, but the Promise .
This is the code snippet:
radarPing: function() {
console.log("ENTER (inside)");
Promise.all([
radar(-8.20917,114.62177,-9.28715,115.71243)
]).then(function(results) {
var ping = results;
console.log("PING1:");
console.log(ping);
var cleanData = jZen(ping);
console.log("PING2: ", cleanData);
self.sendSocketNotification("NEW_DATA", ping); //"PING"
return cleanData; //ping;
});
console.log("EXIT (inside)");
},
readData: function() {
//const myfile = 'modules/MMM-FlightsAbove/demo.json'; // The demo API use improper JSON
var radarData = "";
radarData = this.radarPing();
console.log("The DATA:\n", radarData);
/* if ( radarData === "" ) {
}
*/ //let cleanData = jZen(data);
//let cleanData = jZen(radarData);
let cleanData = radarData;
if (isJSON(cleanData) ) {
this.sendSocketNotification("NEW_DATA", cleanData);
} else {
// So WTF is it?
console.log("- JSON: false");
console.log("- isAO(dirty): " + isAO(radarData));
console.log("- isAO(clean): " + isAO(cleanData));
console.log("- Data:\n", radarData);
}
},
...
});
// To check if something is JSON
function isJSON(str) {
try { return (JSON.parse(str) && !!str); }
catch (e) { return false; }
}
// To check if something is an Array or Object (parsed JSON)
function isAO(val) {
return val instanceof Array || val instanceof Object ? true : false;
}
// --------------------------------------------------------------------------
// What: A dirt simple JSON cleanup function that also compactifies the data
// NOTE: - Only use on flat and trustworthy ASCII JSON data!
// - Cannot handle any characters outside [A-Za-z0-9_\-]. (e.g. UTF-8)
// - Using remote data without further sanitation is a security risk!
// --------------------------------------------------------------------------
const re1 = /([A-Za-z0-9_\-]+):/gm; // use const to make sure it is compiled
function jZen(juice) {
//let re1 = /([A-Za-z0-9_\-]+):/gm; // Find all ASCII words $1 before an ":"
//let data = juice;
let str = "";
str = juice.replace(/\s/gm, ''); // Remove all white-space
str = str.replace(/\'/gm, '\"'); // Replace all ' with "
str = str.replace(re1, '\"$1\":'); // Replace $1: with "$1":
//console.log("Dirty JSON is:\n" + data.toString() );
//console.log("Clean JSON is:\n" + str);
return str;
}
The output is:
...
ENTER (inside)
EXIT (inside)
The DATA:
undefined
- JSON: false
- isAO(dirty): false
- isAO(clean): false
- Data:
undefined
PING1:
[ [ { id: '108be389',
timestamp: 1519647028,
registration: 'PK-GQL',
flight: 'QG8816',
callsign: 'CTV8816',
...
As you can see, PING2 never happens…