Write-json: tinyest JSON serialization crate

Twice this week I needed to produce some tiny JSON, where something like serde would be an overkill. So, I wrote a very small JSON serlization library, which doesn't have macros, traits or dependencies:

write-json

Here's what a real world usage looks liks:

fn to_json(&self, mut obj: write_json::Object<'_>) {
    self.host.to_json(obj.object("host"));
    let timestamp = self.timestamp.duration_since(UNIX_EPOCH).unwrap();
    obj.number("timestamp", timestamp.as_secs() as f64);
    obj.string("revision", &self.revision);
    let mut metrics = obj.object("metrics");
    for (k, (value, unit)) in &self.metrics {
        metrics.array(k).number(*value as f64).string(unit);
    }
}

I also like how "cute" the API and implementation turned out to be! Take a look at the source to see how lifetimes & Drop work together to enforce object boundaries.

2 Likes

That's a nice diff, much more concise :slight_smile:

Mind, I'm still trying to get my head around what the array(s) will actually look like in the resulting JSON.

Does it end up as something like?:

{
...
"metrics": {
    "key1": [ 5.0, "ms" ],
    "key2": [ 15.0, "hz" ],
    "key3": [ 53.0, "cm" ],
}

Without much idea what metrics rust analyser takes :wink:

I guess the Drop occurs after each loop of

for (k, (value, unit))

To close of those arrays

Yes, you are correct on both points.