Search code examples
javascriptc++jsonduktape

Using json objects in duktape


everybody. I've just integrated duktape in my c++ code so that I'm able to use javascript.

But the problem I can't solve right now : how to use json objects in javascript.

Assume I've got some javascript like

function hi(person) {
    print ('hi, ' + person.name );
}

And json object :

{
    'name' : 'duktape'
}

So now I need to call function hi with an argument of this json in my cpp code.

duk_eval_string(ctx, "function hi(person) {print ('hi, ' + person.name );}");
    duk_push_global_object(ctx);
    duk_get_prop_string(ctx, -1, "hi" ); // pushes function from loaded script to stack

    auto json = "{'name' : 'duktape' }";
    duk_push_string(ctx, json);
    duk_pcall(ctx, 1);

The output I get tells, that object is not correct

hi, undefined

Would like to head any suggestions on who should be done to get it working! Thank's for your time :)


Solution

  • You need to use duk_json_decode:

    char *json = "{\"name\": \"duktape\"}";
    duk_push_string(ctx, json);
    duk_json_decode(ctx, -1);
    duk_pcall(ctx, 1);
    duk_pop_2(ctx);
    

    Output:

    hi, duktape
    

    Note that your original json is not valid, you need to use " as string delimiters instead of '.

    Depending on what you really needs, you could also create the object manually:

    duk_idx_t obj_idx = duk_push_object(ctx);
    duk_push_string(ctx, "duktape");
    duk_put_prop_string(ctx, obj_idx, "name");
    duk_pcall(ctx, 1);
    duk_pop(ctx);