如何在Node.js插件中返回JSON内容

我正在做一个Node.js扩展,我想返回一个json格式的对象,而不是一个json格式的string。

#include <node.h> #include <node_object_wrap.h> using namespace v8; void ListDevices(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = Isolate::GetCurrent(); HandleScope scope(isolate); std::string json = "[\"test\", \"test2\"]"; args.GetReturnValue().Set(String::NewFromUtf8(isolate, json.c_str())); } void InitAll(Handle<Object> exports) { NODE_SET_METHOD(exports, "listDevices", ListDevices); } NODE_MODULE(addon, InitAll) 

如何做呢 ?

 var addon = require("./ADDON"); var jsonvar = JSON.parse(addon.listDevices()); console.log(jsonvar); 

实际上,在这个部分,我想删除JSON.parse

顺便说一句,是我吗,还是很难find文件? 我尝试了谷歌,但很多内容是过时的,在v8.h,有趣的function没有logging。

谢谢 ;)

如果要返回JS对象或数组,请参阅节点addon文档 (因为您正在使用节点v0.11.x,所以忽略较早的v8语法)。 与链接示例中创build普通对象不同,请改用Array 。

你不能这样做。 JSON是一种序列化格式。 它使用string来传递数据。 您需要parsing该string以形成JS对象。 这必须在某个时候完成。

换句话说,不存在“JSON格式化对象”这样的事情。 你正在考虑的对象可能是Javascript对象,它不是一个string,当然不是一个C ++对象。 string只是代表对象,它必须被转换。

这应该做到这一点(节点0.12 +):

 void ListDevices(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = args.GetIsolate(); // create a new object on the v8 heap (json object) Local<Object> obj = Object::New(isolate); // set field "hello" with string "Why hello there." in that object obj->Set(String::NewFromUtf8(isolate, "hello"), String::NewFromUtf8(isolate, "Why hello there.")); // return object args.GetReturnValue().Set(obj); } 

简而言之,您的代码将返回一个stringString::NewFromUtf8(isolate, ...)而不是对象Object::New(isolate)