简体   繁体   English

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

[英]Accessing JSON.stringify from node.js C++ bindings

I'm writing node.js bindings and I want to generate JSON string from v8::Object instances. 我正在编写node.js绑定,我想从v8 :: Object实例生成JSON字符串。 I want to do it in C++. 我想用C ++来做。 Since node.js already has JSON.stringify , I would like to use it. 由于node.js已经具有JSON.stringify ,所以我想使用它。 But I don't know how to access it from the C++ code. 但是我不知道如何从C ++代码访问它。

You need to grab a reference to the global object, and then grab the stringify method; 您需要获取对全局对象的引用,然后获取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));

Some of the node API's have changed from the publishing of the OP. 一些节点API已从OP的发布中更改。 Assuming a node.js version 7.7.1, the code transforms to something along the lines of; 假设使用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);
}

Basically, the code gets the JSON object from the engine, obtains a reference to the function stringify of that object, and then calls it. 基本上,代码从引擎获取JSON对象,获取对该对象的函数stringify的引用,然后对其进行调用。 The code is tantamount to the javascript; 该代码等同于javascript;

var j = JSON.stringify(obj);

Further v8 based alternatives include using the JSON class. 基于v8的其他替代方案包括使用JSON类。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM