6

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 ;)

3 Answers 3

3

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).

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

0

You cannot do that. JSON is a serialisation format. It uses strings to pass the data. You need to parse that string to form the JS object. This must be done at some point.

In other words there is no such thing as a "JSON formatted object". The object you are thinking of is probably the Javascript object which is not a string and is certainly not a C++ object. The string just represents the object, and it must be converted.

1 Comment

@mscdex's answer makes me think that the OP is actually asking if he can create a the C++ representation of a javascript object in the V8 engine which node.js runs on. I took the OP at his word on creating a JS object directly from JSON.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.