Skip to content

Instantly share code, notes, and snippets.

@wakita
Created November 6, 2015 09:04
Show Gist options
  • Save wakita/f91561fc1a2d711f3eaa to your computer and use it in GitHub Desktop.
Save wakita/f91561fc1a2d711f3eaa to your computer and use it in GitHub Desktop.
QtにおいてECMAScriptを実行し、その結果をJSONで受け取ること。
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QtScript>
int main(int argc, char *argv[]) {
QGuiApplication app(argc, argv);
QQmlApplicationEngine appEngine;
appEngine.load(QUrl(QStringLiteral("qrc:/main.qml")));
QScriptEngine scriptEngine;
QString script = "var x = { a: true, b: 'c', c: 7, d: [ 1, 2, 3 ] }; JSON.stringify(x, null, 2);";
QJsonDocument json = QJsonDocument::fromJson(scriptEngine.evaluate(script).toString().toUtf8());
QJsonObject x = json.object();
qDebug() << "a: " << x["a"].toBool() << ", b: " << x["b"].toString() << ", c: " << x["c"].toInt();
auto arr = x["d"].toArray();
qDebug("d:");
for (int i = 0; i < arr.size(); i++) {
qDebug() << " " << arr[i].toInt();
}
return app.exec();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment