从node.js C++绑定访问JSON.stringify

Jay*_*esh 10 c++ json node.js

我正在编写node.js绑定,我想从v8 :: Object实例生成JSON字符串.我想用C++做.由于node.js已经有了JSON.stringify,我想用它.但我不知道如何从C++代码访问它.

log*_*yth 5

您需要获取对全局对象的引用,然后获取stringify方法;

Local<Object> obj = ... // Thing to stringify

// Get the global object.
// Same as using 'global' in Node
Local<Object> global = Context::GetCurrent()->Global();

// Get JSON
// Same as using 'global.JSON'
Local<Object> JSON = Local<Object>::Cast(
    global->Get(String::New("JSON")));

// Get stringify
// Same as using 'global.JSON.stringify'
Local<Function> stringify = Local<Function>::Cast(
    JSON->Get(String::New("stringify")));

// Stringify the object
// Same as using 'global.JSON.stringify.apply(global.JSON, [ obj ])
Local<Value> args[] = { obj };
Local<String> result = Local<String>::Cast(stringify->Call(JSON, 1, args));
Run Code Online (Sandbox Code Playgroud)