2009-08-25

Storing JSON as Protocol Buffers

I love JSON (and I think that my HyperJSON format is the best data model in existence) but for some reason or other, I always have trouble with JSON libraries for mainstream programming languages.

As a way out, I have defined my own data model, similar to JSON's, but I'm serializing it as Protocol Buffers using this .proto file:

message Data {

optional Text text = 1;
optional Link link = 2;
optional Entry entry = 3;
optional Feed feed = 4;
optional Date date = 5;
optional Bool bool = 6;

message Text {
required string string = 1;
}

message Link {
required string href = 1;
optional string rel = 2 [default = ""];
optional bool rev = 3 [default = false];
}

message Feed {
repeated Data element = 1;
}

message Property {
required string key = 1;
required Data value = 2;
}

message Entry {
repeated Property property = 1;
}

message Date {
required int64 millis = 1;
}

message Bool {
required bool bool = 1;
}

}

There are a lot of different ways to store JSON in PB, and the details are pretty much irrelevant. An important point though is how the JSON objects (Entry) are stored: simply as a list of Property objects.

It's the same as with object-oriented programming: you never want to model extensible records (business objects, documents, etc) directly as objects (Protocol Buffers in this case). Instead, you want to compose your business objects from your programming language's native objects.

See Being poor at modeling is essential to OOP.

No comments: