63 lines
2.1 KiB
C
63 lines
2.1 KiB
C
#include "cell.h"
|
|
|
|
static JSValue js_json_encode(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) {
|
|
if (argc < 1) return JS_ThrowTypeError(ctx, "json.encode requires at least 1 argument");
|
|
|
|
JSValue global = JS_GetGlobalObject(ctx);
|
|
JSValue json = JS_GetPropertyStr(ctx, global, "JSON");
|
|
JSValue stringify = JS_GetPropertyStr(ctx, json, "stringify");
|
|
|
|
JSValue args[3];
|
|
args[0] = argv[0]; // value
|
|
args[1] = (argc > 1) ? argv[1] : JS_NULL; // replacer
|
|
args[2] = (argc > 2) ? argv[2] : JS_NewInt32(ctx, 1); // space, default 1
|
|
|
|
JSValue result = JS_Call(ctx, stringify, json, 3, args);
|
|
|
|
JS_FreeValue(ctx, stringify);
|
|
JS_FreeValue(ctx, json);
|
|
JS_FreeValue(ctx, global);
|
|
|
|
if (argc <= 2) JS_FreeValue(ctx, args[2]);
|
|
|
|
return result;
|
|
}
|
|
|
|
static JSValue js_json_decode(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) {
|
|
if (argc < 1) return JS_ThrowTypeError(ctx, "json.decode requires at least 1 argument");
|
|
|
|
if (!JS_IsString(argv[0])) {
|
|
JSValue err = JS_NewError(ctx);
|
|
JS_SetPropertyStr(ctx, err, "message",
|
|
JS_NewString(ctx, "couldn't parse text: not a string"));
|
|
return JS_Throw(ctx, err);
|
|
}
|
|
|
|
JSValue global = JS_GetGlobalObject(ctx);
|
|
JSValue json = JS_GetPropertyStr(ctx, global, "JSON");
|
|
JSValue parse = JS_GetPropertyStr(ctx, json, "parse");
|
|
|
|
JSValue args[2];
|
|
args[0] = argv[0]; // text
|
|
args[1] = (argc > 1) ? argv[1] : JS_NULL; // reviver
|
|
|
|
JSValue result = JS_Call(ctx, parse, json, argc > 1 ? 2 : 1, args);
|
|
|
|
JS_FreeValue(ctx, parse);
|
|
JS_FreeValue(ctx, json);
|
|
JS_FreeValue(ctx, global);
|
|
|
|
return result;
|
|
}
|
|
|
|
static const JSCFunctionListEntry js_json_funcs[] = {
|
|
JS_CFUNC_DEF("encode", 1, js_json_encode),
|
|
JS_CFUNC_DEF("decode", 1, js_json_decode),
|
|
};
|
|
|
|
JSValue js_json_use(JSContext *js) {
|
|
JSValue export = JS_NewObject(js);
|
|
JS_SetPropertyFunctionList(js, export, js_json_funcs, sizeof(js_json_funcs)/sizeof(JSCFunctionListEntry));
|
|
return export;
|
|
}
|