【问题标题】:Accessing JSON.stringify from node.js C++ bindings从 node.js C++ 绑定访问 JSON.stringify
【发布时间】:2013-04-06 02:34:37
【问题描述】:

我正在编写 node.js 绑定,我想从 v8::Object 实例生成 JSON 字符串。我想用 C++ 来做。由于 node.js 已经有JSON.stringify,我想使用它。但我不知道如何从 C++ 代码中访问它。

【问题讨论】:

    标签: c++ json node.js


    【解决方案1】:

    从 OP 的发布开始,一些节点 API 发生了变化。假设 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);
    

    【讨论】:

      【解决方案2】:

      需要抓取全局对象的引用,然后抓取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));
      

      【讨论】:

      • 有些事情在 V8 API 中明显改变了: 1. 没有GetCurrent,通常你使用isolate-&gt;GetCurrentContext()-&gt;Global() 从隔离中获取全局。 2. 没有String::New(),通常你想要String::NewFromUTF8()。不要认为这可以证明另一个答案是合理的,但如果你更新你的答案,它会被调用。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-08
      • 1970-01-01
      • 2022-09-23
      • 1970-01-01
      • 1970-01-01
      • 2016-01-10
      相关资源
      最近更新 更多