Agent using millisecond

I’m having the opposite issue as this person: https://discourse.electricimp.com/discussion/2304/json-webservice-returns-very-large-numbers

I need to send a millisecond timestamp to an API that I do not control. I’m fine with using a second-based timestamp & just adding some zeros, but when I use format("%d000",time()), in some JSON, it will always format it as a string (as it should!), but I need to send it as an int.

Has anyone found a workaround for this in squirrel?

The agent has microsecond time available:

local d=date(time()); server.log(format("%d.%06d", d.time, d.usec));

See https://electricimp.com/docs/squirrel/system/date/

You either need to construct the JSON “manually” in Squirrel (it’s not hard), or perhaps use http.jsonencode() with a placeholder string and then replace that string with your large integer.

Peter

If it helps here’s some manually encoded JSON code
ms_enc = { "key1": ms "volts": volts} uniqueid = "xyz123" urlstring = "http://someserver.net/" + uniqueid + "/impdata.php" http.put(urlstring, { "Content-Type": "application/json" }, http.jsonencode(ms_enc)).sendsync()

Have you considered the JSONEncoder class?

This should do the trick:
`#require “JSONEncoder.class.nut:1.0.0”

class TimeStamp {
_date = null;

constructor(d=null){
    if(d==null){
        _date = date()
    } else{
        _date = d
    }
}

function _serializeRaw() {
    return format("%d.%06d", _date.time, _date.usec)
}

};

server.log(JSONEncoder.encode({
a = 123,
b = [1, 2, 3, 4],
c = TimeStamp,
d = 5.125,
e = TimeStamp(),
f = null,
g = true,
h = “Some
ùnicode\rstring ø∆ø”
}))

//Logs {“a”:123,“c”:{"_date":null},“b”:[1,2,3,4],“e”:1472688866.071246,“d”:5.125,“g”:true,“f”:null,“h”:“Some
ùnicode\rstring ø∆ø”}`

Parsing the long timestamps back into the Agent is a bit trickier… I use my arbitrary precision big number class, the JSONDecoder, and the following function to deal with it (once it is a big, I can more easily cast to int32 as required by calling split(bigNum.ToString(), “.”)[0]).

`
function JSONParseBig(s){
return JSONParser.parse(s, function(val, type){
if(“number” == type)
return Big(val)

    return val;
})

}
`