我正在编写node.js绑定,我想从v8 :: Object实例生成JSON字符串。我想用C ++做。由于node.js已经有JSON.stringify
,我想使用它。但我不知道如何从C ++代码中访问它。
答案 0 :(得分: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));
答案 1 :(得分:1)
某些节点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的替代方案包括使用JSON
类。
auto str = v8::JSON::Stringify(v8::Isolate::GetCurrent()->GetCurrentContext(), obj).ToLocalChecked();
v8::String::Utf8Value json{ str };
return std::string(*json);