Send JSON to agent with http post

I’m trying to set up a simple html form to test json input to an agent. From the dev wiki:

Example code for JSON delivery

Here is some HTML+Javascript that sends a table (containing a string called “x” and an integer called “y”) into the Plan as a JSON string. Note that you’ll need to replace the “https:…” URL with the URL to your own HTTP in block.

`

string: number: `

When I try to use this to send to my agent and use http.jsondecode(), it throws an exception. Using this code on the agent:

http.onrequest(function(request, response) { try { local t = http.jsondecode(request.body); response.send(200, "OK"); } catch (e) { response.send(500, "Exception"); } });

Can you do server.log() of the request.body?

This is the result with server.log(request.body):

2013-09-08 21:15:00 UTC+7: [Agent] value=%7B+%22x%22%3A+%22abcd%22%2C+%22y%22%3A+1234+%7D&example1=abcd&example2=1234

Hi Spencer,

I think you have an escape issue. I format my data like this and it works perfectly.

var sendForm = function(data){ // Format the request data into stringified JSON return(JSON.stringify(data)) }

Imp code local requestObj = http.jsondecode(request.body);

Hope this works!

Agent tested with your html and works a few things. I think you need to use the newer https://agent.electricimp.com/agent id url and a html form is not JSON just a set of key value pairs.

I written a few tutorials cover web to agent/imp this might help this one turns imp pins on and off http://industrialinternet.co.uk/eimp/t2_digital_out/index.html

`function requestHandler(request,res){
res.header(“Access-Control-Allow-Origin”, “*”);

if(request.method=="POST"){
   
    server.log("body:"+request.body);
    local keys = http.urldecode(request.body);
    foreach(idx,val in keys){
        server.log("index="+idx+" value="+val+"\

");
}
res.send(200,“OK.POST”);
}

}

http.onrequest(requestHandler);`

You’re mixing up an old-style web page (“HTTP in block”) with new-style (onRequest) agent code. “HTTP in blocks” automatically pluck the “value” field out of the url-encoded POST body for you, parse it as JSON, and send it to your planner (blueprint) input node. Now that everyone’s using agents, you needn’t go such a roundabout route.

Peter

Thanks for all of the replies.

Peter, that makes sense, thank you.

If I have the option of delivering data to the agent as JSON, or urlencoded key/value pairs…is there any advantage to either method?