c++ - 从 node.js C++ 绑定(bind)访问 JSON.stringify

标签 c++ json node.js

我正在编写 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/

相关文章:

c++ - 在 C++ 中调用模板

C++ 调试断言错误

c++ - #define 在 C++ 中的效用

python - pretty-print JSON

c++ - 如何在 C++ 的 Qt Creator 中向 TableView 添加自定义对象?

json - 将多态案例类转换为 json 并返回

java - Android应用程序中的JSON解析

javascript - NOT 在 Node/ Mongoose 中不起作用

javascript - 即使提供了 Pingdom 凭据也会丢失

javascript - ES6 使用构造函数参数设置此属性