MantisBase v0.4.9
Loading...
Searching...
No Matches
duk_json.h
Go to the documentation of this file.
1
8
9#ifndef MANTISBASE_SCRIPTING_DUK_JSON_H
10#define MANTISBASE_SCRIPTING_DUK_JSON_H
11
12#include <dukglue/dukglue.h>
13#include <nlohmann/json.hpp>
14#include "script_json.h"
15
16namespace dukglue {
17 namespace types {
18 template<>
19 struct DukType<nlohmann::json> {
20 typedef std::true_type IsValueType;
21
22 template<typename FullT>
23 static nlohmann::json read(duk_context *ctx, duk_idx_t arg_idx) {
24 if (!(duk_is_object(ctx, arg_idx) || duk_is_string(ctx, arg_idx) || duk_is_number(ctx, arg_idx) ||
25 duk_is_boolean(ctx, arg_idx) || duk_is_null(ctx, arg_idx))) {
26 duk_error(ctx, DUK_ERR_TYPE_ERROR, "Argument %d: expected a JSON value", static_cast<int>(arg_idx));
27 }
28
29 duk_dup(ctx, arg_idx);
30 const char *encoded = duk_json_encode(ctx, -1);
31 const std::string text = encoded ? encoded : "null";
32 duk_pop(ctx);
33
34 try {
35 return nlohmann::json::parse(text);
36 } catch (const nlohmann::json::exception &ex) {
37 duk_error(ctx, DUK_ERR_TYPE_ERROR, "%s", ex.what());
38 }
39 return {};
40 }
41
42 template<typename FullT>
43 static void push(duk_context *ctx, const nlohmann::json &value) {
44 if (value.is_null()) {
45 duk_push_null(ctx);
46 return;
47 }
48 const std::string text = value.dump();
49 duk_push_string(ctx, text.c_str());
50 duk_json_decode(ctx, -1);
51 }
52 };
53
54 // Arguments use MbScriptJson. A nlohmann::json parameter is wrapped in an
55 // array by dukglue's tuple conversion; see script_json.h.
56 template<>
57 struct DukType<mb::MbScriptJson> {
58 typedef std::true_type IsValueType;
59
60 template<typename FullT>
61 static mb::MbScriptJson read(duk_context *ctx, duk_idx_t arg_idx) {
62 return mb::MbScriptJson(DukType<nlohmann::json>::read<nlohmann::json>(ctx, arg_idx));
63 }
64
65 template<typename FullT>
66 static void push(duk_context *ctx, const mb::MbScriptJson &value) {
67 DukType<nlohmann::json>::push<nlohmann::json>(ctx, value.value);
68 }
69 };
70 }
71}
72
73#endif
Definition duk_json.h:17
Definition duk_json.h:16
Definition api_keys.h:35
JSON value carried into a Duktape method without going through nlohmann::json.
static mb::MbScriptJson read(duk_context *ctx, duk_idx_t arg_idx)
Definition duk_json.h:61
std::true_type IsValueType
Definition duk_json.h:58
static void push(duk_context *ctx, const mb::MbScriptJson &value)
Definition duk_json.h:66
static void push(duk_context *ctx, const nlohmann::json &value)
Definition duk_json.h:43
static nlohmann::json read(duk_context *ctx, duk_idx_t arg_idx)
Definition duk_json.h:23
std::true_type IsValueType
Definition duk_json.h:20
Definition script_json.h:19
nlohmann::json value
Definition script_json.h:20