aboutsummaryrefslogtreecommitdiffstats
path: root/src/plugins/lua/bindings/json.cpp
blob: c238f4f213bfb0c46a6fe71d8558b50f70960b77 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// Copyright (C) 2024 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0
#include "../luaengine.h"

#include <QJsonArray>
#include <QJsonDocument>

namespace Lua::Internal {

void setupJsonModule()
{
    registerProvider("Json", [](sol::state_view lua) -> sol::object {
        sol::table json = lua.create_table();
        json["encode"] = &toJsonString;

        json["decode"] = [](sol::this_state l, const QString &str) -> sol::table {
            QJsonParseError error;
            auto doc = QJsonDocument::fromJson(str.toUtf8(), &error);
            if (error.error != QJsonParseError::NoError)
                throw sol::error(error.errorString().toStdString());

            return toTable(l.lua_state(), doc);
        };

        return json;
    });
}

} // namespace Lua::Internal