Adding Data To JSON Object Before Sending

My imp currently reads pins and sends it to the agent (as a string formed from a json-like object), which then sends it to my server.

The agent is keeping some metrics that I would like to package with the json. I’m unsure how to do this. Currently this is not working:

    local incoming = http.jsondecode(response.body);
    //incoming["report_counter"] = report_counter; 
    //incoming.report_counter = report_counter;
    response.body = http.jsonencode(incoming);

If I just used substring to remove the final } from the json object and tagged the string (also not working):

response_body = response_body.substring(0, -1) + ' "agent_metric":' + agent_metric_var + ' "}'

If I tweak it as a string then I wouldn’t be encoding/decoding json, which might actually be “quicker”, but it feels like an ugly hack.

Any advice?

For the first, I think you want incoming.report_counter <- report_counter; the “new slot” operator <- is required when creating a new key in a table.

For the second, I think you also need to add a comma.

To be any more help, we’d need to see the actual errors, or a description of what isn’t working.

Peter

+1 peter! this fixed it:

    local incoming = http.jsondecode(response.body);
    incoming.report_counter <- report_counter;
    response.body = http.jsonencode(incoming);

You mentioned the “new slot” operator; I was in fact trying to create a new key in the existing table (rather than replacing existing data). My actual error message was that the key didn’t exist. I suppose another fix would have been to add the key at the device level prior to transmitting and just setting it to -1 or something, then replacing it in the agent.

Follow up question for bonus points: where can I read about the “new slot” operator, and should i be using it in order to create a new key instead of what I did (which apparently did create a new key)?

You did the right thing; I unhelpfully got the operator wrong in my reply. I’ll edit it now. See Squirrel Programming Guide | Dev Center

Peter

Got it, thanks so much for the follow up and for helping me solve my problem! :slight_smile: