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:


Here's what a real world usage looks liks:

fn to_json(&self, mut obj: write_json::Object<'_>) {
    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.


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.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.