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

我正在编写node.js绑定,我想从v8 :: Object实例生成JSONstring。 我想用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)); 

一些节点API已经从OP的发布中改变了。 假设一个node.js版本7.7.1,代码转换为沿着;

 std::string ToJson(v8::Local<v8::Value> obj) { if (obj.IsEmpty()) return std::string(); v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::HandleScope scope(isolate); v8::Local<v8::Object> JSON = isolate->GetCurrentContext()-> Global()->Get(v8::String::NewFromUtf8(isolate, "JSON"))->ToObject(); v8::Local<v8::Function> stringify = JSON->Get( v8::String::NewFromUtf8(isolate, "stringify")).As<v8::Function>(); v8::Local<v8::Value> args[] = { obj }; // to "pretty print" use the arguments below instead... //v8::Local<v8::Value> args[] = { obj, v8::Null(isolate), v8::Integer::New(isolate, 2) }; v8::Local<v8::Value> const result = stringify->Call(JSON, std::size(args), args); v8::String::Utf8Value const json(result); return std::string(*json); } 

基本上,代码从引擎获取JSON对象,获得对该对象的函数stringify的引用,然后调用它。 该代码无异于javascript;

 var j = JSON.stringify(obj); 

更多基于v8的select包括使用JSON类。

 auto str = v8::JSON::Stringify(v8::Isolate::GetCurrent()->GetCurrentContext(), obj).ToLocalChecked(); v8::String::Utf8Value json{ str }; return std::string(*json);