I'm making a Node.js extension, and I would like to return a json format object, instead of a json-formatted 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)
How can it be done ?
var addon = require("./ADDON");
var jsonvar = JSON.parse(addon.listDevices());
console.log(jsonvar);
Actually, in this part, I would like to remove the JSON.parse
By the way, is it me, or it is really difficult to find documentation ? I tried on google, but a lot of content was out of date, and in v8.h, interesting functions weren't documented.
Thank you ;)
If you want to return a JS object or array, see the node addon docs (disregard the older v8 syntax since you are using node v0.11.x). Instead of creating a plain Object as in the linked example, use an Array instead.
This should do it (node 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);
}
In short, your code is returning a string String::NewFromUtf8(isolate, ...)
instead of an object Object::New(isolate)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With