Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/38.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何在Node.js加载项中返回JSON内容_C++_Node.js - Fatal编程技术网

C++ 如何在Node.js加载项中返回JSON内容

C++ 如何在Node.js加载项中返回JSON内容,c++,node.js,C++,Node.js,我正在做一个Node.js扩展,我想返回一个json格式的对象,而不是json格式的字符串 #include <node.h> #include <node_object_wrap.h> using namespace v8; void ListDevices(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = Isolate::GetCurrent(); Han

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

#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)
实际上,在这一部分中,我想删除JSON.parse

顺便问一下,是我,还是真的很难找到文档?我在google上试过,但是很多内容都过时了,在v8.h中,有趣的函数没有被记录下来


谢谢;)

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


换句话说,没有所谓的“JSON格式的对象”。您所考虑的对象可能是JavaScript对象,它不是字符串,当然不是C++对象。字符串仅表示对象,必须对其进行转换。

如果要返回JS对象或数组,请参阅(忽略旧的v8语法,因为您使用的是节点v0.11.x)。不要像链接示例中那样创建普通对象,而是使用一个替代对象。

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

void列表设备(常量函数callbackinfo&args){
隔离*隔离=args.GetIsolate();
//在v8堆上创建一个新对象(json对象)
本地对象=对象::新建(隔离);
//在该对象中设置字段“hello”和字符串“Why hello there.”
obj->Set(String::NewFromUtf8(隔离,“你好”),String::NewFromUtf8(隔离,“为什么在那里你好”);
//返回对象
args.GetReturnValue().Set(obj);
}

简而言之,您的代码正在返回一个字符串<代码>字符串::NeNoFrutoF8(隔离,…)<代码>,而不是对象<代码>对象::新的(隔离)< /C> > ./P>@ MSCDEX的回答使我认为OP实际上是在问是否可以创建一个JavaScript对象的C++表示,它是No.js运行的V8引擎。我接受了他关于直接从JSON创建JS对象的建议。

var addon = require("./ADDON");

var jsonvar = JSON.parse(addon.listDevices());
console.log(jsonvar);
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);
}