我正在编写 node.js 绑定(bind),我想从 v8::Object 实例生成 JSON 字符串。我想用 C++ 来做。由于 node.js 已经有 JSON.stringify
,我想使用它。但我不知道如何从 C++ 代码中访问它。
最佳答案
需要抓取全局对象的引用,然后抓取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));
关于c++ - 从 node.js C++ 绑定(bind)访问 JSON.stringify,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15990445/