by duped · 3y ago · 0 comments
"duration": {
"days": 15,
"hours": 5,
"seconds": 20
}
Now it's not the job of your JSON parser to understand the semantics of your data. It's your input validator's - which is how it should be, imo.Note you will have to have some fallible conversion step from whatever JSON chooses to represent that data as anyway.
2023-08-24T20:30:00Z
versus "time" : {
"year" : 2023,
"month" : 8,
"day" : 24,
"hour" : 20,
"minute" : 30,
"second" : 0,
"timezone" : "UTC",
}
Call me lazy, but tryping the latter took me 20 times longer. I totally would use it for internal state, but I would not store it like that or expose that to users ever.Durations optimized for storage without ambiguity would be the tuple (u64, u32, u8) where the first value is seconds, second value is nanoseconds (if precision is needed) and final value is epoch.
Durations displayed to a user wouldn't ever be stored so the point is kind of moot.
Optimizing for "time it takes someone to write it once" is kind of dumb since it happens once while reading it happens often, and parsing even more likely.
And it's really nice in some circumstances (such as the file names case) that alphabetical sort is identical to chronological sort.
And just... why would you spend 10x the space to represent timestamps when ISO timestamps (or, well, RFC 3339) works just fine?
With your example, I would need to create custom parsing logic, and handle a dynamic number of JSON fields. But if a TimeSpan class had JSON deserialization built in based on the ISO8601 format, then I wouldn't need to do anything special. That's the benefit of using the standards. Same if I wanted to convert the JSON stringified format into a postgres time span there isn't any special parsing logic I need to do.
Yes, it's just a string in JSON, so it's not semantically special. But other languages that have a TimeSpan type could take advantage of the standard serialized format.
Here is an example of what it could look like in F#, no special logic for deserializing into a custom type:
type MyEvent = {
myDuration: TimeSpan;
createdAt: DateTimeOffset;
eventId: string;
}
let rawJson =
"""
{
"myDuration":"P15DT5H0M20S",
"createdAt": "2023-08-24T20:30:00Z",
"eventId": "e_1234"
}
"""
let myEvent = JsonSerializer.Deserialize<MyEvent>(json = rawJson)But either way you need multiple pieces of data for the duration to be correct and useful. Without the created-at time in your example the duration will be invalid in the presence of leap years/seconds.
If you want to unambiguously encode a duration of time, it needs to be in the smallest unambiguous unit that is meaningful (usually seconds/nano seconds). That will allow your duration to be correctly used without any additional logic/metadata packed along with it.