nodejs/node-addon-examples

JSON process in Node-addon-api

KunwarAkanksha opened this issue · 2 comments

I am very new to this..
Can anyone please give me a simple illustration to catch the json ({key:value, key:value......}) data in node-addon-api and then process that data (like sum of values ). I am able to catch the json in form of string at c++ node-addon but when i am catching the json as an object I cannot assign the Napi::Object to my own object

Hi @KunwarAkanksha,
the simplest way to handle json data is to use the functions JSON.parse (https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse) and JSON.stringify (https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) that you can retrieve from global object.
I report a simple example below:

Napi::Value Parse(const Napi::CallbackInfo& info) {
    // Get string that represents your json
    Napi::String json_string = info[0].As<Napi::String>();
    Object json = env.Global().Get("JSON").As<Object>();
    Function parse = json.Get("parse").As<Function>();
    Napi::Object json_obj = parse.Call(json, { json_string });
    // Now you can do whatever you want with the object I'm simply returning it back
    return json_obj;
}

Napi::Value Stringify(const Napi::CallbackInfo& info) {
    // Get string that represents your json
    Napi::Object json_obj = info[0].As<Napi::Object>();
    Object json = env.Global().Get("JSON").As<Object>();
    Function stringify = json.Get("stringify").As<Function>();
    Napi::String json_string = parse.Call(json, { json_obj });
    // Now you can do whatever you want with the string I'm simply returning it back
    return json_string;
}

Napi::Object Init(Napi::Env env, Napi::Object exports) {
    exports["parse"] = Napi::Function::New(env, Parse);
    exports["stringify"] = Napi::Function::New(env, Stringify);
}
NODE_API_MODULE(NODE_GYP_MODULE_NAME, Init)

I hope that this help you.

Thanks Very much @NickNaso it has solved my problem..