Search code examples
jsonsocket.ioarduino-esp8266

i want to add variable into json object in arduino


so i have a socket io app, i need to emit json but have no idea how to insert variable into json object

this the example from : https://github.com/timum-viw/socket.io-client#emit

socket.emit("plainString", "\"this is a plain string\"");
socket.emit("jsonObject", "{\"foo\":\"bar\"}");

and this is my code :

char* variable = "this is a string";

socket.emit("jsonObject", "{\"foo\":\"variable\"}");

result in socket io

[
"foo":"variable"
]

expected result :

 [
    "foo":"this is a string"
    ]

Solution

  • I found the answer:

    void SendSocket(String socketname,String foo,String bar){
      String Data = "{\"_foo\":\"" + foo + "\",\"_bar\":\"" + bar + "\"}";
      socket.emit(socketname.c_str(), Data.c_str());
    }
    

    And here is how to use it

    SendSocket("jsonObject","this is foo","this is bar");
    

    And this is the code to catch the event from Arduino (in server):

    socket.on("jsonObject",function data(){
    console.log(data);
    });
    

    The result will be:

    [
    _foo:"this is foo",
    _bar:"this is bar"
    ]