Looking for feedback – library to generate JSON within a smart contract

I had been working on a smart contract where I needed to generate some JSON within a smart contract. I was originally piecing things together by string concatenating everything and thought there must be a better way. When I couldn’t find an already existing solution, I ended up extracting that logic out into this library.

One thing I have tried to do is to make things as gas-optimized as possible, as I quickly found out string manipulation can get costly quickly.


function generateJSON() external pure returns (string memory) {
JsonWriter.Json memory writer;

writer = writer.writeStartObject();

writer = writer.writeStringProperty(“Product”, “PC”);
writer = writer.writeUintProperty(“YearsOld”, 5);
writer = writer.writeIntProperty(“LowestTemp”, -30);
writer = writer.writeStringProperty(“CPU”, “Intel”);

writer = writer.writeStartArray(“Drives”);
writer = writer.writeStringValue(“500 gigabyte SSD”);
writer = writer.writeStringValue(“2 terabyte hard drive”);
writer = writer.writeEndArray();

writer = writer.writeEndObject();

return writer.value;

Calling `generateJSON()` would return the following (not pretty-printed):

“Product”: “PC”,
“YearsOld”: 5,
“LowestTemp”: -30,
“CPU”: “Intel”,
“Drives”: [
“500 gigabyte SSD”,
“2 terabyte hard drive”

I would love any and all feedback if there’s things I can improve or change. Thanks!

What do you think?

10 Points
Upvote Downvote

Leave a Reply

Your email address will not be published. Required fields are marked *

GIPHY App Key not set. Please check settings


Crypto Sentiment Survey (February 2019) | by Zachary DeWitt | WING VC

This is not a full DD. This is a post saying do not ****ing buy Krispy Kreme stock – this is a sunken ship.