Have this code:
auto obj_idx = duk_push_object( ctx );
duk_push_string( ctx, "key" );
duk_push_string( ctx, "value" );
duk_put_prop( ctx, obj_idx );
duk_push_string( ctx, "key2" );
duk_push_string( ctx, "value" );
duk_put_prop( ctx, obj_idx );
duk_put_global_string( ctx, "obj" );
How insert new object in obj? No matter how hard I try to insert a nested object, it doesn’t work. Either crash or not inserted.
{
"key": "value",
"key2": "value",
"newObj": {
"newKey": "value"
}
}
I put the following code into the Duktape hello
example and it produced the right result:
auto obj_idx = duk_push_object( ctx );
duk_push_string( ctx, "key" );
duk_push_string( ctx, "value" );
duk_put_prop( ctx, obj_idx );
duk_push_string( ctx, "key2" );
duk_push_string( ctx, "value" );
duk_put_prop( ctx, obj_idx );
auto nested_idx = duk_push_object(ctx);
duk_push_int(ctx, 2019);
duk_put_prop_string(ctx, nested_idx, "year");
duk_put_prop_string(ctx, obj_idx, "nested");
duk_put_global_string( ctx, "obj" );
duk_eval_string(ctx, "print(JSON.stringify(obj))");
The key thing to remember is that duk_put_prop
and duk_put_prop_string
take one value off the stack, while duk_push_*
pushes a value on the stack.