Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing JSON.stringify from node.js C++ bindings

Tags:

c++

json

node.js

I'm writing node.js bindings and I want to generate JSON string from v8::Object instances. I want to do it in C++. Since node.js already has JSON.stringify, I would like to use it. But I don't know how to access it from the C++ code.

like image 917
Jayesh Avatar asked Apr 13 '13 16:04

Jayesh


1 Answers

You need to grab a reference to the global object, and then grab the stringify method;

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));
like image 197
loganfsmyth Avatar answered Oct 06 '22 06:10

loganfsmyth