I have a file settings.js which includes an array with arrays of settings:
[
// [property, section, hex-address, Bytes to read/write, type, lsb, msb, options]
["AEC Control" , "AEC Control", 0x10300, 4, "bool", 0, 0],
["Shutter Mode", "Sensor Mode", 0x10104, 4, "bool", 0, 0],
["Nb ADC", "Sensor Mode", 0x10108, 4, "bool", 0, 0],
...
]
As you can see the file just contains the array value without assignment to a variable and without semicolon at the end.
The settings.js is put inside the resources.qrc:
<RCC>
<qresource prefix="/js">
<file alias="CameraSettings">resources/settings.js</file>
</qresource>
</RCC>
I read the settings.js with QFile. Here is the code to evaluate the javascript:
QFile cameraSettingsJsFile(":/js/CameraSettings");
if(!cameraSettingsJsFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
throw std::exception("CameraSettingsProperties-file not valid!");
};
QJSEngine jsengine;
std::cout << "Output: '" << QTextStream(&cameraSettingsJsFile).readAll().toStdString() << "';" << std::endl;
QJSValue settingsArrayJSValue = jsengine.evaluate(QTextStream(&cameraSettingsJsFile).readAll());
Because of the Output line i know that the file is read correctly however QJSEngine won't evaluate the value correctly. Because settingsArrayJSValue.isArray() evaluates to false i called all is...() functions on settingsArrayJSValue. Only settingsArrayJSValue.isUndefined() evaluates to true.
I also tried this:
jsengine.evaluate("x=" + QTextStream(&cameraSettingsJsFile).readAll() + ";");
Then settingsArrayJSValue.isObject() evaluates to true (which is in a way expected when speaking of the js world) but i also get a SyntaxError: Expected token 'numeric literal'.
My final goal here is to parse the setttings array. Therefore i want to JSON.stringify the evaluated array and work with Qt QJson classes:
QJSValueList stringifyArguments;
stringifyArguments.append(settingsArrayJSValue);
QString evaluationResultString = jsengine
.evaluate(QString("JSON.stringify"))
.call(stringifyArguments)
.toString();
QJsonArray jsonCameraSettingsArray =
QJsonDocument::fromJson(evaluationResultString.toUtf8()).array();
The problem was this line:
Because i read the file there, when trying to read from
cameraSettingsJsFilea second timeQTextStream(&cameraSettingsJsFile).readAll()will be an empty string because the pointer is moved to the end of the stream.So QJSEngine works fine...