如何在Node.js插件中返回JSON内容
How to return JSON content in Node.js Addon
我正在做一个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)
怎么做呢?
var addon = require("./ADDON");
var jsonvar = JSON.parse(addon.listDevices());
console.log(jsonvar);
实际上,在这一部分中,我想删除JSON.parse
顺便问一下,是我的问题,还是真的很难找到文档?我在谷歌上尝试过,但是很多内容都过时了,而且在v8.h中,有趣的功能没有记录。
如果你想返回一个JS对象或数组,请参阅node插件文档(因为你使用的是node v0.11.x,所以请忽略旧的v8语法)。与在链接示例中创建普通对象不同,使用Array代替。
应该这样做(节点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);
}
简而言之,您的代码返回的是字符串String::NewFromUtf8(isolate, ...)
,而不是对象Object::New(isolate)
。
你不能那样做。JSON是一种序列化格式。它使用字符串来传递数据。您需要解析该字符串以形成JS对象。这个必须在某个时刻完成。
换句话说,没有"JSON格式的对象"这样的东西。你正在考虑的对象可能是Javascript对象,它不是字符串,当然也不是c++对象。字符串只表示对象,必须对其进行转换。
相关文章:
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- 在c++中使用nlohmann从类到json的转换
- 什么时候在C++中返回常量引用是个好主意
- 你能重载对象变量名本身返回的内容吗
- 为什么 Serial.println(<char[]>);返回随机字符?
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 保存json文件后如何返回文件路径
- 我想将字符串转换为 Json 格式并返回字符串向量作为答案
- 为什么 libcurl 在 JSON 响应字符串后返回"0"?
- 返回时,JSON :: Value会更改
- C 返回函数的函数返回JSON数组通过Nlohmann Json.hpp
- JSON CPP ISMEMBER()始终返回true
- 当标题中指定文本/纯文本时,易趣API返回JSON
- Json cpp asCstring() 存储在变量中时返回空字符串
- jsoncpp:按名称访问JSON对象,返回可变引用,如果未找到则不创建对象
- 对 Boost JSON 解析器的调用永远不会返回
- 在json中返回QtQSqlQuery
- 比较从函数返回的两个std::string常量(两个json精神get_str())1-liner
- 对 'json11::Json::d ump(std::string&) const' collect2 的未定义引用:错误:ld 返回 1 个退出状态
- 如何在Node.js插件中返回JSON内容